我是 jQuery 的新手,我对 $(this) 的使用有点困惑。这是一个简单的示例代码:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function change()
{
$(this).html("STOP");
}
</script>
</head>
<body>
<h2 onclick="change()">GO</h2>
</body>
</html>
在这里,如果我单击文本“GO”,那么我希望它会自行更改为“STOP”。但它不起作用。我错过了什么?
最佳答案
尝试将 this
传递给引用 h2
元素的函数:
<h2 onclick="change(this)">GO</h2>
然后您可以将该参数传递给您的函数:
function change(el) {
$(el).html("STOP");
}
或者更好的是,您可以使用 .click()
事件处理程序:
$('h2').click(function() {
$(this).html("STOP");
});
关于javascript - 如何使用 jQuery $(this) 更改使用 "onclick"事件的元素的 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26250536/