[英]Jquery how to use $(this) to get value of clicked item?
I have trouble getting value of particular item that I'd clicked 我无法获得我点击过的特定物品的价值
<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()
, but it will return the value of 1st button("Yes) even if I clicked the 2nd button("No") $(this).find("button").html()
,但是即使我单击了第二个按钮(“否”),它也会返回第一个按钮的值(“是”)。 $(this).find("p").html()
, will return value of 1st $(this).find("p").html()
,将返回值1st $(this)
to get the value of item I clicked? $(this)
获得我点击的项目的价值? It is because $(this).click
event listener is added to document
object and not any specific html element. 这是因为
$(this).click
事件侦听器已添加到document
对象,而不是任何特定的html元素。
$(document).ready(function(){
$('button,p').on('click',function(){
alert($(this).html());
});
});
plunker: https://jsfiddle.net/wx38rz5L/1743/ 塞子: https ://jsfiddle.net/wx38rz5L/1743/
If you are trying to get each button's html on click, use this. 如果您试图在单击时获取每个按钮的html,请使用它。
$('button').click(function () {
alert($(this).html());
});
this
in your click handler is always the document (which you've bound the handler to), so that doesn't help anything. this
在点击处理程序始终是文件(你已经绑定的处理程序),这样就不会什么帮助。 Instead, use something like 相反,使用类似
$(document).click(function(e){
if ($(e.target).is("button"))
console.log($(e.target).text());
} else {
console.log("not clicked (directly) on a button");
}
});
or rather just 或只是
$(document).on("click", "button", function(e){
console.log($(this).text());
});
Bind the click event on both button
and get the content of the html element with innerHTML
. 绑定两个
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>
You have to detect which $(this) is binded for ? 您必须检测哪个$(this)被绑定? Try something like 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(); }); });
Try this. 尝试这个。
$(document).ready(function() {
$(this).click(function(event) {
alert(event.target.innerHTML);
});
});
In jQuery event.target
always refers to the element that triggered the event. 在jQuery中,
event.target
始终指触发事件的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.