使用Jquery从页面上的许多重复类中获取特定元素

Using Jquery to get a specific element out of many repeated classes on the page

本文关键字:获取 元素 许多重 Jquery 使用      更新时间:2023-09-26

我有一段重复的代码。

<div class='commentfloatleft'>
                <button type='button' class='button2' onclick='upvote($id8)'>
                    <img src='images/likebutton.png'    class='upvoteimage' width='12' height='12' alt='PearlSquirrel'/>
                </button>
                <button type='button' class='button2' onclick='downvote($id8)'>
                    <img src='images/unlikebutton.png' width='12' height='12' alt='PearlSquirrel'/>
                </button>
            </div>

当我点击onclick代码时,upvote是这样的:

function upvote(box){
$(this).siblings('.upvoteimage').load('upvote.php?box=' + box);
}

我想尽一切办法让它发挥作用。get函数正在工作,但我看不到".upvoteimage"有任何更改。有人知道如何解决这个问题吗。我们将不胜感激。谢谢

试试这个方法:为你的"按钮"元素设置一个类"upvote":

<div class='commentfloatleft'>
                <button type='button' class='button2 upvote' id='$id8'>
                    <img src='images/likebutton.png'    class='upvoteimage' width='12' height='12' alt='PearlSquirrel'/>
                </button>
                <button type='button' class='button2' onclick='downvote()'>
                    <img src='images/unlikebutton.png' width='12' height='12' alt='PearlSquirrel'/>
                </button>
            </div>​

并使用这个JS代码:

$(".upvote").on("click",function(){
    var box=$(this).attr("id");
    $(this).find('.upvoteimage').attr("src",'upvote.php?box=' + box);
    return false;
}​);​

您的代码显示兄弟姐妹,但是.upvoteimage不是兄弟姐妹而是子代。请尝试使用find/childs。

函数中可能不存在$(this)。也许您应该将onclick事件移到脚本块中。jQuery有一些很棒的特性,不适合使用内联代码。

尝试这个

HTML

  <div class='commentfloatleft'>
                    <button type='button' class='button2' onclick='upvote(this,'x27$id8'x27)'>
                        <img src='images/likebutton.png'    class='upvoteimage' width='12' height='12' alt='PearlSquirrel'/>
                    </button>
                    <button type='button' class='button2' onclick='downvote($id8)'>
                        <img src='images/unlikebutton.png' width='12' height='12' alt='PearlSquirrel'/>
                    </button>
                </div>

YOur jQuery代码:

function upvote(obj,box){
$(obj).children('.upvoteimage').load('upvote.php?box=' + box);
}

您正在引用按钮的同级,并对upvoteimage类的同级进行筛选。

你想做的是参考兄弟姐妹,然后选择他们班上的孩子

$(this).siblings('.button2').children('.upvoteimage').load('upvote.php?box=' + box);

这是一个孩子而不是兄弟姐妹这是因为它没有发生

你可以试试

$(this).siblings('.button2' > '.upvoteimage') 

我认为一些类似的东西会工作

您应该使用.on()来绑定事件,而不是内联。

upvote函数中,this是窗口对象,而不是单击的按钮。

具有upvote类的img是按钮的子级,而不是兄弟级。

您不能将任何内容加载到img标记中,它是一个空标记