Jquery右选择器用于元素/按钮使用.html()动态加载?

时间:2016-06-16 04:16:04

标签: jquery html

用于使“我的按钮”工作的正确'选择器'是什么? 我搜索过这个网站,似乎没有一个对我有用吗?

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="index, all" />
<title>Example</title>
</head>

<body>
    <div id="result"><!--results-->
    </div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
    $( document ).ready(function() {
        //generate table
        htmlx='<table class="table table-condensed">';
        htmlx+='<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>';
        htmlx+='</table>';
        $('#result').html(htmlx);               
    });

    $("#bt_kgt2").on( "click", function() {
        alert ("button clicked!");
    });
</script>
</body> 
</html>

1 个答案:

答案 0 :(得分:1)

您正在尝试在添加元素之前绑定click事件处理程序。在将元素添加到dom之后,您有两个绑定click事件处理程序的选项。

&#13;
&#13;
$(document).ready(function() {
  //generate table
  htmlx = '<table class="table table-condensed">';
  htmlx += '<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>';
  htmlx += '</table>';
  $('#result').html(htmlx);
  $("#bt_kgt2").on("click", function() {
    alert("button clicked!");
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
  <!--results-->
</div>
&#13;
&#13;
&#13;

或使用event delegation来监听动态添加的元素

&#13;
&#13;
$(document).ready(function() {
  //generate table
  htmlx = '<table class="table table-condensed">';
  htmlx += '<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>';
  htmlx += '</table>';
  $('#result').html(htmlx);

});

$('#result').on("click", "#bt_kgt2", function() {
  alert("button clicked!");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
  <!--results-->
</div>
&#13;
&#13;
&#13;