Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅在具有相同类名的特定项上运行Javascript函数_Javascript_Function - Fatal编程技术网

仅在具有相同类名的特定项上运行Javascript函数

仅在具有相同类名的特定项上运行Javascript函数,javascript,function,Javascript,Function,如果不使用jQuery,如何仅对一个与其他项具有相同类名的项运行函数 我有一个WordPress循环,每个项目都有一个按钮,用于在div中的图像上运行函数 以下是在页面上重复10次的循环项: <li id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="block bg-white relative mt-7 work__image-wrap">

如果不使用jQuery,如何仅对一个与其他项具有相同类名的项运行函数

我有一个WordPress循环,每个项目都有一个按钮,用于在div中的图像上运行函数

以下是在页面上重复10次的循环项:

 <li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
     <div class="block bg-white relative mt-7 work__image-wrap">
       <a href='<?php echo types_render_field("website-url"); ?>' target="_blank">
        <?php echo '<img class="item absolute pin-t w-full h-auto pin-l" src="'. $workitem .'" alt="'. the_title() .'"/>';?>
       </a>
      </div>
       <div class="button-wrap">
        <button id="portScroll">Scroll Down</button>
       </div>
       <div class="p-2">
        <h3 class="text-black font-bold pt-4 pb-2"><a class="text-black font-bold" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
       </div>
    </li>
用类替换按钮的id属性:

在函数scrollDown中,获得如下图像:

var portImg = this.parentNode.parentNode.querySelector('img.item');
或者,或者:

var portImg = this.closest('li').querySelector('img.item');

当然,这就是我要做的:

作用{ const posts=document.getElementsByClassName'post'; forlet i=0,m=posts.length;i当前函数无法正常工作,因为没有id为item的元素。此外,您的HTML将有多个id相同的元素,这是无效的HTML。您所说的仅在循环中的项上是什么意思?循环生成了多个项,对吗?为什么要提到jQuery?您知道如何使用jQuery解决这个问题吗?我不想使用jQuery,而是想节省人们使用jQuery回答问题的时间。循环中有多个项目。这里习惯用工作代码更新我的问题还是保持原样?谢谢!这很有效。谢谢你的JS课程!这是一个很好的答案,但我不想使用ID,这样就可以应用于任何类型的循环。非常感谢。
for (const button of document.querySelectorAll('button.portScroll')) {
    button.addEventListener("click", scrollDown);
}
var portImg = this.parentNode.parentNode.querySelector('img.item');
var portImg = this.closest('li').querySelector('img.item');