javascript - .click() 对 child 不起作用

标签 javascript jquery

我有一些 HTML,例如:

<html>
<body>
    <div id="parent">
         <input id="child1" onclick="clickedInline();" style="z-index:999" disabled readonly>Child One</input>
         <input id="child2">Child Two</input>
    </div>
</body>
</html>

还有一些像这样的jquery:

// Wait for page to load
$(function(){

    // Log clicked item
    $('*').click(function(){
        console.log($(this).prop("tagName")+'#'+$(this).attr('id'));
    });

    // I want this to happen
    $('#child1').click(function(){
        alert("It worked!");
    });

    // I've tried this too
    $('#child1').on("click", function(){
        alert("It worked!");
    });

    // And even this
    $('#parent').on("click", '#child1', function (){
        alert("It worked!");
    });

});

// This doesn't work either
function clickedInline(){
    alert("It worked!");
}

当我点击#child1时,没有弹出警报,并且会记录以下内容:

DIV#parent
BODY#undefined
HTML#undefined

.click() 事件似乎仅在父元素上触发,而不是在子元素上触发。我不希望它在单击 #child2 时触发。

最佳答案

您好,您的代码似乎可以与警报框配合使用,但您的结束正文和 html 标记似乎确实是错误的。

// Wait for page to load
$(function(){

    // Log clicked item
    $('*').click(function(){
        console.log($(this).prop("tagName")+'#'+$(this).attr('id'));
    });

    // I want this to happen
    $('#child1').click(function(){
        alert("It worked!");
    });

    // I've tried this too
    $('#child1').on("click", function(){
        alert("It worked!");
    });

    // And even this
    $('#parent').on("click", '#child1', function (){
        alert("It worked!");
    });

});

// This doesn't work either
function clickedInline(){
    alert("It worked!");
}
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
</head>
<body>
    <div id="parent">
         <input id="child1" onclick="clickedInline();" style="z-index:999">Child One</input>
         <input id="child2">Child Two</input>
    </div>
</body>
</html>

关于javascript - .click() 对 child 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43442931/

相关文章:

javascript - 关闭 colorbox 并将父窗口重定向到特定的 url

jquery - float 元素上的 Bootstrap Popover

javascript - 具有过滤值的 jQuery 目标选择器属性并添加新类

javascript - lodash 合并和组合对象

javascript - 为什么我的 React 组件不断重新渲染?

javascript - 如何清空 Angular 4 中的可观察对象

javascript - Android 浏览器 JavaScript 无法正确测量高度

javascript - 无法将数据写入 Node JS 中的文件

Javascript 按钮有两个功能。提交并单击

javascript - 如何获取按钮单击 Angular 对象值?