我有一个按钮,我想在单击该按钮时使用 jQuery 记录内部文本。我知道如何使用 id 来获取按钮的文本 ($("#testID").text()
),但这对我来说不是一个选择。我想使用 $(this)
关键字而不是 id,但我不知道该怎么做。
html:
<button id="testID" onclick="getButtonText()">Button Text</button>
JavaScript:
function getButtonText() {
console.log("this text = " + $(this).text()); //not working
}
最佳答案
传入这个
html:
<button id="testID" onclick="getButtonText(this)">Button Text</button>
JavaScript:
function getButtonText(self) {
console.log("this text = " + $(self).text()); //not working
}
否则,this
将是 window
对象
关于javascript - 使用 $(this) 和 jQuery 访问内部文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31549567/