Javascript 如何检查同一事件的多个元素
对多个元素执行相同的行为 //htmlJavascript 如何检查同一事件的多个元素,javascript,jquery,html,facebook,Javascript,Jquery,Html,Facebook,对多个元素执行相同的行为 //html <div id=""> <input type="hidden" value="1258" /> value of user id to make friend </div> <div id=""> <input type="hidden" value="2595" /> </div> <div id=""> <input type="hidden" value="
<div id="">
<input type="hidden" value="1258" /> value of user id to make friend
</div>
<div id="">
<input type="hidden" value="2595" />
</div>
<div id="">
<input type="hidden" value="2563" />
</div>
我试过这样使用它
$("#div1,#div2,#div3").click(function(){
$x=$("hidden").value(); // the value is friendID
//then send $x to the server using Ajax
});
但是我有更多的元素代码增长,它不是动态的,同样的,如果我想做出喜欢按钮的行为,我有多个喜欢按钮我怎么知道哪个帖子和哪个喜欢试试
<div id="div1">
<input type="hidden" value="1258" /> value of user id to make friend
</div>
$("[id^=div]").click(function() {
$x=$(this).find("[type=hidden]").val();
});
要交朋友的用户id的值
$(“[id^=div]”。单击(函数(){
$x=$(this.find(“[type=hidden]”)val();
});
或
要交朋友的用户id的值
$(“.classSelector”)。单击(函数(){
$x=$(this.find(“[type=hidden]”)val();
});
您的选择器都错了。div
元素没有任何id
属性,因此按原样选择它们将不起作用。其次,您要使用:hidden
或input[type=“hidden”]
来选择隐藏的输入。最后,要获取表单元素的值,请使用val()
,而不是value()
如果要使其动态化,则代码将用于x
个div
元素,请使用类来识别它们,然后在处理程序中使用此
来访问引发事件的元素,如下所示:
<div class="foo">
<input type="hidden" value="1258" /> value of user id to make friend
</div>
<div class="foo">
<input type="hidden" value="2595" />
</div>
<div class="foo">
<input type="hidden" value="2563" />
</div>
你是故意使用==的吗???@TJ这只是一个打字错误。。你可以帮我编辑,而不是投反对票(好吧,这不仅仅是一个打字错误……答案还是有问题的……OP的html中没有id
,比如div1,div2
等…@TJ OP刚刚给出了一个这样的示例,我只是继承了它并回答了他,如果我像你说的那样做了任何压倒性的事情,人们会说是谁给了y这个建议您的答案仍然是错误的。OP的html没有与您的选择器匹配的div。如果您的答案需要对OP的html进行任何修改,您必须明确提及它。例如。
<div class="classSelector">
<input type="hidden" value="1258" /> value of user id to make friend
</div>
$(".classSelector").click(function() {
$x=$(this).find("[type=hidden]").val();
});
<div class="foo">
<input type="hidden" value="1258" /> value of user id to make friend
</div>
<div class="foo">
<input type="hidden" value="2595" />
</div>
<div class="foo">
<input type="hidden" value="2563" />
</div>