使用Jquery从页面上的许多重复类中获取特定元素
Using Jquery to get a specific element out of many repeated classes on the page
我有一段重复的代码。
<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标记中,它是一个空标记
相关文章:
- 如何在jQuery中获取元素的形式
- 通过id和class属性获取元素
- Javascript:Can't使用getElementById获取元素
- 使用jquery.html()获取元素本身的html
- 如何从iframe内部获取元素
- Javascript函数获取元素内容
- 使用模板后,使用Angular获取元素属性值
- 获取元素类名的部分
- 从JSON.parse获取元素
- 获取元素内部的缩写
- 在不引用文档的情况下使用AngularJS获取元素
- 如何获取元素's的title属性
- 使用Javascript,获取元素的方法是什么,基于打开和关闭标记之间的文本
- Javascript获取元素背景图像,但消除了“;url()”;
- Javascript:按类获取元素,但跳过某个类
- 当display:none时,getElementById()无法获取元素
- 我的ID获取元素不起作用
- 如何获取元素:使用javascript和CORS悬停背景
- 能够获取元素长度,但不能获取内部 HTML
- 如何使用jQuery在模板kendo UI中获取元素类