【问题标题】:Why is this simple jQuery snippet not working?为什么这个简单的 jQuery 片段不起作用?
【发布时间】:2011-07-01 01:52:47
【问题描述】:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
function foo() {
    $(this).parent('li').append('hello world');
}
</script>

<ul>
    <li><img src="http://www.gravatar.com/avatar/a3981906ca415e0ec3e051076b71b0cd?s=32&d=identicon&r=PG" onClick="foo()" /></li>
    <li><img src="http://www.gravatar.com/avatar/8ec1383b240b5ba15ffb9743fceb3c0e?s=32&d=identicon&r=PG" onClick="foo()" /></li>
</ul>

我正在尝试将字符串“hello world”附加到包含刚刚单击的图像的&lt;li&gt;

【问题讨论】:

    标签: javascript jquery click append


    【解决方案1】:

    无需附加onclick。使用 jQuery 就可以了

    $('li').click(function(){
    $(this).append('hello world')
    });
    

    http://jsfiddle.net/tFr5y/查看工作示例

    【讨论】:

    • 不是把这个功能加到那个页面的每一个里吗?
    • 要将其限制为特定的 li 集,您需要指定 UL id。例如:$('li','#ulid').click(..).
    • +1 :用于 jQuey 特定的事件处理解决方案。添加 jQuery 但不使用它来注册事件处理程序是浪费能量 :)
    【解决方案2】:

    因为在foo 函数中this 是未定义的,所以函数不知道是哪个元素触发了事件。

    <html>
    <head>
    <script src="jquery.js"></script>
    <script>
    
        function foo(elem)
        {
            $(elem).parent('li').append('asdf');
    
        }
    </script>
    </head>
    <body>
        <li><img  src="source" onclick="foo(this)" /></li>
    
        <li><img  src="source" onclick="foo(this)" /></li>
    
    </body>
    </html>
    

    【讨论】:

      【解决方案3】:

      两个变化

      [1]在foo中添加一个参数

      function foo(me) {
          $(me).parent('li').append('hello world');  
      }
      

      [2]在onClick中传入foo中的参数

      <ul>
          <li><img src="http://www.gravatar.com/avatar/a3981906ca415e0ec3e051076b71b0cd?s=32&d=identicon&r=PG" onClick="foo(this)" /></li>
          <li><img src="http://www.gravatar.com/avatar/8ec1383b240b5ba15ffb9743fceb3c0e?s=32&d=identicon&r=PG" onClick="foo(this)" /></li>
      </ul>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-25
        • 2012-06-25
        相关资源
        最近更新 更多