你好,为什么我的按钮B不工作


Hello, Why my button B does not work?

为什么我的按钮B不显示警报弹出?

下面是我的代码在单独的文件

. html:

<html>
<body>
    <input type="button" class="popup" value="BUTTON A"/><br>
    <input type="button" class="displaymeh" value="SHOW"/>
<div id="display">
</div>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>

。php:

<?php
    echo "<input type='button' class='popup2' value='BUTTON B'/>";
?>

. js:

$(".popup").on('click', function(){
    alert("HELLO WORLD!");
});
$(".popup2").on('click', function(){
        alert("HELLO WORLD! 2");
});
$(".displaymeh").on('click', function(){
    $.ajax({
        url: 'display.php',
        success: function(data) {
        $('#display').html(data);
        }
    });
});

我将按钮放在。php中的原因,是因为我计划在php中显示数据库表和按钮来管理数据库,如delete.

编辑:不,这与。on('click')和。click()之间的差异是不一样的,为什么我在1小时内就得到了负面的投票,我永远不会知道。

每页只允许有1个相同名称的idid属性不能重复。你可以单独绑定BUTTON B,给它一个不同的ID (id="popup2"),例如,或者给它一个类而不是一个ID,并使用类绑定器代替:

你的HTML也是无效的。创建如下输入:

<input type="button" class="popup" value="BUTTON A" />
<br>
<input type="button" class="displaymeh" value="SHOW" />
<input type='button' class='popup' value='BUTTON B' />

另一个问题是元素在页面加载时根本不存在。每当向dom添加新的HTML时,都必须重新执行绑定!像这样:

JS:

$(function() {
  //set the button bindings initially
  setButtonBindings();
  $(".displaymeh").on('click', function() {
    $.ajax({
      url: 'display.php',
      success: function(data) {
        $('#display').html(data);
        //re-set the button bindings after html has been added
        setButtonBindings();
      }
    });
  });
});
function setButtonBindings() {
  $('.popup').off("click"); //so it won't trigger multiple times
  $('.popup').on("click", function() {
    alert("I like cheese");
    return false;
  });
}

——从现在开始尝试使用.on("click")和这样的绑定,而不是.click();。它更可靠,.click()等是已弃用的函数。它们甚至在jQuery 3.x

中被完全删除了。