简体   繁体   English

如何将click事件附加到以编程方式创建的jquery对象上?

[英]How do you attach a click event to a jquery object created programmatically?

I'm writing some jquery to programmatically build a list of links and I'd like to attach a click() event to each link. 我正在编写一些jquery以编程方式构建链接列表,我想将click()事件附加到每个链接。 I'm having trouble getting the click function to fire. 我无法启动点击功能。 Can anyone point me in the right direction on how to do this? 谁能为我指出正确的方法?

This is what I have so far: 这是我到目前为止的内容:

<!doctype html>
<html>
<head>
<title></title>

<script type="text/javascript" src="helper/jquery-1.4.2.min.js"></script>  
<script type="text/javascript">                                         
$(document).ready(function() {
    var markup = '<li><a href="#myLink1">some link</a></li>';
    var $newLink = $(markup);
    $newLink.appendTo('.myLinks ul');
    $newLink.show();

    $("ul.myLinks li").click(function() {
        alert('hello');
    });
});
</script> 

</head>

<body>
  <div class="myLinks">
    <ul>
    </ul>
  </div>

</body>
</html>

Your mistake is here: 您的错误在这里:

$("ul.myLinks li").click(function() {
    alert('hello');
});

That should be .myLinks ul li instead, as your myLinks class is on a <div> , not a <ul> . 应该是.myLinks ul li ,因为您的myLinks类位于<div> ,而不是<ul>

If that still doesn't work, then Evgeny is right in that you should be attaching click events to your <a> s and not their containing <li> s. 如果那仍然不起作用,那么Evgeny是正确的,因为您应该将click事件附加到您的<a>而不是它们包含的<li>

In addition to what BoltClock said, it looks like you're attaching the event handler to the list items, rather than the hyperlinks inside them. 除了BoltClock所说的,看起来您正在将事件处理程序附加到列表项上,而不是将其附加到列表项中。 Try $(".myLinks ul li a") . 尝试$(".myLinks ul li a")

I would also test the selector to make sure it's returning what you want. 我还将测试选择器,以确保它返回您想要的东西。 Step through it in Firebug or do something like alert($(".myLinks ul li a")[0]); 在Firebug中逐步执行此操作或执行alert($(".myLinks ul li a")[0]);

You could try something like this: 您可以尝试这样的事情:

$('div.myLinks ul')
  .append( '<li><a href="#myLink1">some link</a></li>' )
  .delegate( 'a','click', function(e){
    e.preventDefault();
    alert('hi');
  });​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Here's a working example . 这是一个有效的例子

Of course, the .append() would more likely be a bunch of li s -- something you can build any number of ways: 当然, .append()更可能是一堆li -您可以通过多种方式构建它:

var $bunchOfLi = $('<li><a href="#myLink1">some link</a></li>')
  .add('<li><a href="#myLink2">another link</a></li>')
  .add('<li><a href="#myLink3">yet another link</a></li>');

...and thus: ...因此:

.append( $bunchOfLi )

...as in this working example . ...如本示例所示

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

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