javascript - 使用 $(this) 和 jQuery 访问内部文本

标签 javascript jquery this

我有一个按钮,我想在单击该按钮时使用 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/

相关文章:

javascript - 如何在基于JS的聊天室中查找用户的IP?

javascript - 如何在 react 导航中有条件地隐藏 Tab?

javascript - 我可以使用 PropTypes 来表示 prop 是 Promise 吗?

javascript - 如何按值查找输入元素 ID?

java - 为什么不能在这里使用 'this' 关键字?

javascript - WordPress - JS 和 CSS 文件被 301 重定向?

javascript - JavaScript 中的数字选择器

javascript - JQuery BorderRadius 在 mouseout 中不执行动画

javascript - 通过标签名称 [this] 获取元素?

java - android访问扩展类中的对象