[英]Jquery how to use $(this) to get value of clicked item?
我无法获得我点击过的特定物品的价值
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(this).click(function(){
alert($(this).find("button").html());
});
});
</script>
</head>
<body>
<p>test 1</p>
<p>test 2</p>
<button>Yes</button>
<button>No</button>
</body>
</html>
$(this).find("button").html()
,但是即使我单击了第二个按钮(“否”),它也会返回第一个按钮的值(“是”)。 $(this).find("p").html()
,将返回值1st $(this)
获得我点击的项目的价值? 这是因为$(this).click
事件侦听器已添加到document
对象,而不是任何特定的html元素。
$(document).ready(function(){
$('button,p').on('click',function(){
alert($(this).html());
});
});
塞子: https ://jsfiddle.net/wx38rz5L/1743/
如果您试图在单击时获取每个按钮的html,请使用它。
$('button').click(function () {
alert($(this).html());
});
this
在点击处理程序始终是文件(你已经绑定的处理程序),这样就不会什么帮助。 相反,使用类似
$(document).click(function(e){
if ($(e.target).is("button"))
console.log($(e.target).text());
} else {
console.log("not clicked (directly) on a button");
}
});
或只是
$(document).on("click", "button", function(e){
console.log($(this).text());
});
绑定两个button
上的click事件,并使用innerHTML
获取html元素的内容。
$(document).ready(function() { $('button').click(function(event) { alert(event.target.innerHTML); }); });
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <body> <p>test 1</p> <p>test 2</p> <button>Yes</button> <button>No</button> </body> </html>
您必须检测哪个$(this)被绑定? 尝试这样的事情:
<button class="btn red btn-xs editbtn" type="button" value="${rs.id}" value="${rs.id}">
$(function(){ $('.editbtn').click(function(e){ common.showSpinner(); var idbbpdtd = $(this).val(); }); });
尝试这个。
$(document).ready(function() {
$(this).click(function(event) {
alert(event.target.innerHTML);
});
});
在jQuery中, event.target
始终指触发事件的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.