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

Veg*_*tus 3 html javascript jquery

尝试理解为什么在alert("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");
      });
  });
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

And*_*ker 5

您正在用divid"relation-states" 替换整个内容,这也是删除事件处理程序(因为删除了附加处理程序的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");
  });
Run Code Online (Sandbox Code Playgroud)

或者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");
}
Run Code Online (Sandbox Code Playgroud)