我想要带有“按钮文本”的提醒
这不起作用:
<button onclick="fun()">button text</button>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>
function fun(){
alert($(this).html()); //I've also tried $(this).val() and $(this).text()
}
</script>
但以下工作正常:
<script>
function fun(){
alert("some plain text");
}
</script>
最佳答案
您尝试记录的 this
是 Window
对象,您无法在其上使用 innerHTML
。相反,传递 button
元素的上下文。
function fun(context) {
alert($(context).html());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="fun(this)">button text</button>
关于javascript - 为什么 'this' 关键字在以下 html 代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54495819/