javascript - 为什么 'this' 关键字在以下 html 代码中不起作用?

标签 javascript jquery html

我想要带有“按钮文本”的提醒

这不起作用:

<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>

最佳答案

您尝试记录的 thisWindow 对象,您无法在其上使用 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/

相关文章:

javascript - 递归的子集和 - 我做错了什么?

javascript - jQuery 通过多个行情轮换

javascript - 用于 jquery 布局的自定义切换器

html - 基于其他div动态高度的动态div高度

动画中的Javascript数组拼接

javascript - 控制台输出在 Firefox 29.0.x 上的 Firebug 1.12.x 中不可见

javascript - AJAX 调用后单击更改变量

c# - 动态添加新对象时 Javascript 停止

php - Ajax 显示使用 php 在目录中显示带有图像显示的导航

使用图像提交 JavaScript 表单不起作用