简体   繁体   English

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

[英]How to use ID selector after jQuery html()

It's amazing to try to understand why the function alert("hello") is not generated after clicking more than once... There is some method to do this function is executed? 尝试理解为什么在多次单击后没有生成函数alert("hello")这真是太棒了...有一些方法可以执行此功能吗?

Note that doesn't work after update using html() involving id "press" in button. 请注意,使用html()进行更新后无法正常工作,该按钮包含id“按”按钮。

Any idea? 任何的想法? See: http://jsbin.com/atuqu3 请参阅: http//jsbin.com/atuqu3

JavaScript: 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: 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>

You're replacing the contents of the entire div with id "relation-states", which is also removing event handlers (since DOM nodes with the handlers attached are being removed). 您正在用id“relation-states”替换整个div的内容,这也是删除事件处理程序(因为删除了附加处理程序的DOM节点)。 If you want to bind event handlers to all elements that meet a selector now or in the future, check out live : 如果要将事件处理程序绑定到现在或将来遇到选择器的所有元素,请查看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");
  });

or delegate : 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");
}

When using .html() , you are deleting all the children of that element and replacing them with new ones. 使用.html() ,您将删除该元素的所有子元素并将其替换为新元素。 That means that any event handlers attached to those children are lost. 这意味着附加到这些孩子的任何事件处理程序都会丢失。 You could avoid that by only replacing what you really need to: 你可以通过只替换你真正需要的东西来避免这种情况:

$('#state').html('<option value="Texas">Texas</option>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM