Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么';t$(this).id返回单击的元素';谁的身份证?_Javascript_Jquery - Fatal编程技术网

Javascript 为什么';t$(this).id返回单击的元素';谁的身份证?

Javascript 为什么';t$(this).id返回单击的元素';谁的身份证?,javascript,jquery,Javascript,Jquery,为什么我的this.id在单击时返回未定义的而不是按钮的id?我知道也有一些类似的问题,但这些建议似乎都不适合我。在任何人建议之前,我也尝试过$(this.attr(“id”) 代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width">

为什么我的
this.id
在单击时返回未定义的而不是按钮的id?我知道也有一些类似的问题,但这些建议似乎都不适合我。在任何人建议之前,我也尝试过
$(this.attr(“id”)

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Meh</title>
    </head>
    <body>
      <h2>Hello</h2>
      <button id="warning" class="btn">Button</button>
      <p>Button id: <span id="show"></span></p>
      <script
        src="https://code.jquery.com/jquery-3.1.1.js">
      </script>
      <script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> 
      </script>
      <script type="text/javascript">
        $(".btn").on("click", () => $("#show").html($(this).id));
      </script>
    </body>
</html>

无聊的
你好
按钮
按钮id:

$(“.btn”)。在($(单击),()=>$(“#显示”).html($(this.id));

谢谢

以下是另一种方法:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Meh</title>
    </head>
    <body>
      <h2>Hello</h2>
      <button id="warning" class="btn">Button</button>
      <p>Button id: <span id="show"></span></p>
      <script
        src="https://code.jquery.com/jquery-3.1.1.js">
      </script>
      <script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> 
      </script>
      <script type="text/javascript">
        $('.btn').click(function(event){
            $("#show").html(event.target.id);
        });
      </script>
    </body>
</html>

无聊的
你好
按钮
按钮id:

$('.btn')。单击(函数(事件){ $(“#show”).html(event.target.id); });
因为
不是具有id的元素?因为您使用的是箭头函数。读一读。在这种情况下,您应该使用
$(“.btn”).on(“单击”,函数(){$(“#显示”).html($(this.id)})
$(“.btn”)。在(“单击”、(ev)=>$(“#显示”).html(ev.target.id))或从event@JordanS谢谢“你的建议很管用。谢谢你,驼鹿。”柯林斯兰多,随时欢迎!