2011-08-19 79 views
0

我有一个CSHTML动态形成的锚标签不调用点击功能

<td id="device-body"> 
    <ul> 
     <li id="devicesInOffice"></li> 
    </ul> 
</td> 

,我试图动态填充锚标记列表的L1标签(如下图所示)

function populateDevicesAvailable(deviceType) { 
    if (deviceType.id != "") { 
     $.post(window.getOfficesDevicesUrl, { devicetypeId: deviceType.id }, 
     function (results) { 
      var items = ""; 
      $.each(results, function (i, device) { 
       items += 
"<a id='" + device.Id + "' href= '" + "#" + "'  
       class='devices'  
       onclick='javascript:populateDeviceInfo()'>" + device.Name + "</a>"; 
      }); 

      $("li#devicesInOffice").append(items); 

     }); 
    } 
    else { 
     $("li#devicesInOffice").html(""); 
    } 
}; 


function populateDeviceInfo() { 
} 

populateDeviceInfo函数永远不会被调用。当我单击超链接时,我只会得到一个“对象预期”错误。

我也试过其他方式(下面)来调用该函数,但没有任何工作。

$(".devices").click(function() { 
    populateDeviceInfo(); 
}); 

$("li#devicesInOffice a").click(function() { 
    populateDeviceInfo(); 

有人可以帮我找到一种方法来调用函数。 谢谢,

回答

2

使用live,每次插入元素到DOM动态事件处理程序没有得到重视,然后自动

$(".devices").live('click', function() { 
    populateDeviceInfo(); 
}); 
+0

Thanks.Got现在工作。 – Lavan

+0

很高兴帮助 - – Rafay

0

是的,没错,在处理程序注册后添加的链接不会受到影响。这就是为什么有.live().delegate()方法的jQuery。

Example

+0

Thanks.Got It working now。 – Lavan

+0

@Laven,如果我的回答是正确的,请批准它作为正确答案(点击数字下的空白** V **)。 –

0

如果是动态生成的元素,那么click功能不会影响,因为click只绑定到已经存在的元素。您需要使用live[docs]函数:

$(".devices, li#devicesInOffice a").live("click", function() { 
    populateDeviceInfo(); 
} 

你会发现,你可以同时使用多个jQuery选择。这样,您不必重复您的代码。

+0

Thanks.Got现在工作。 – Lavan

0

使用delegate()[docs]方法处理程序分配给握着你.devices元素的容器。

$(function() { 
    $('#devicesInOffice').delegate('.devices','click', populateDeviceInfo); 
}); 

这会将#devicesInOffice元件上的单个处理程序(只要它是本加载页面时)。

的是,当点击该.devices选择器相匹配的任何嵌套元件上发生的处理程序将被调用。