2013-07-16 20 views
0

我尝试通过Jquery在表中动态创建两个相同的元素,但Id是问题。我尝试根据元素编号创建一个Id,var id =“links”+ i;但是,我不能通过$(“#”)选择这个元素,即使我使用“Links1”作为id选择器。我不知道有什么问题。通过Id选择动态控制

<script type="text/javascript"> 
    $(function() { 
     var number = 2; 
     for (var i = 0; i < number; i++) { 
      var id = "links" + i; 
      var item = $("<td><a id ='" + id + "'>" + i + "</td>"); 
      $("#" + id).click(function() { 
       alert("Great"); 
      }); 
      $("#TrInput").append(item); 
     } 
    }); 
</script> 

<body> 
<form id="form1" runat="server"> 
<div> 
<table><tr id="TrInput"></tr></table> 
</div> 
</form> 

+0

使用'on'代替 –

+0

'click'是'on'的快捷方式,也不会有所作为,除非你使用代表团......在这种情况下, ,从'#form1' – smerny

回答

3

在你结合$('#' + id)时,该元素不会在DOM存在。所以它不绑定点击处理程序。

取而代之的是,绑定到item.click或仅在调用append后绑定。或者,您可以使用事件委托并绑定到document,但对于该解决方案,最好查看jQuery事件委派并查看它是如何工作的。

1

您可以在您刚刚创建的项目直接添加监听...

var item = $("<td><a id ='" + id + "'>" + i + "</td>"); 
item.click(function() { 
     alert("Great"); 
}); 
$("#TrInput").append(item); 

使用一些代表团,这不会是非常实用与正在创建的电流的方式来做到提到ID和ID访问。我会用一个类来选择的,就像这样:

var item = $("<td><a id ='" + id + "' class='itemClass'>" + i + "</td>"); 

,然后你可以改变你的为您的活动选择这样:

$("#form1").on("click", ".itemClass", function() { ... 
0

使用事件代表团。而不是在你的td结合click事件的每一个a

$("#TrInput").on("click", "a", function(e) { 
    e.preventDefault(); //just in case 
    alert("hi!"); 
}); 

所以,既然你tr已经存在它会很乐意委派事件被点击a时处理。而且,如果你tr也是动态的,你会做这样的事情:

$("table").on("click", "tr a", function(e) { 
    e.preventDefault(); //just in case 
    alert("hi!"); 
}); 
-1

在你结合的时候,该元素不会在DOM存在。所以它没有绑定点击处理程序,因为没有要绑定的元素。因此,一个简单的解决方案就是使用授权。现在,使用委托的美妙之处在于,不管元素何时创建,处理程序都被分配给元素。这应该对你有用。 PS:当你必须在旅途中(动态地)创建元素时,你应该尝试使用委托。

+1

'#Links1'你错过了英镑符号。这是事件代表团。这是一个很好的解决方案,但我会建议你解释他做错了什么,以及为什么这个工作:) –

0

更改你的脚本如下:

 $(function() { 
      var number = 2; 
      for (var i = 0; i < number; i++) { 
       var item = $("<td><a id ='links'>" + i + "</td>"); 
       $("#TrInput").append(item); 
      } 
     }); 

一旦创建项目后,使用上/委托方法,因为点击亘古不变的动态创建的元素工作;所以,下一行代码是:

$("#links").on("click",function(){ 
// As now you have two elements with the same ID, make use of: this property; 
    Suppose you want to change the color of that clicked element, that would be: 
$(this).css("color","#0777da"); 
//This effects only the currently selected/clicked element and 
    not every other element with the same Id.. 
});