javascript – 如何在jQuery html()之后使用ID选择器

尝试理解为什么在多次单击后没有生成函数警报(“hello”)这真是太棒了…有一些方法可以执行此功能吗?

请注意,使用html()进行更新后无法正常工作,该按钮包含id“按”按钮.

任何的想法?见:http://jsbin.com/atuqu3

JavaScript的:

$(document).ready(function (){
      $("#press").click(function() {
          $("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');;
          alert("hello");
      });
  });

HTML:

<div id="relation-states">
  <select id="state" name="state">
  <option value="New York">New York</option>
  </select>
  <button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>
  </div>

解决方法

您正在用id“relation-states”替换整个div的内容,这也是删除事件处理程序(因为删除了附加处理程序的DOM节点).如果要将事件处理程序绑定到现在或将来遇到选择器的所有元素,请查看 live

$("#press").live("click",function() {
      $("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');;
      alert("hello");
  });

delegate

$("#relation-states").delegate("#press","click",function() {
          $("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');;
          alert("hello");
}

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...