Javascript 为什么这个简单的jQuery代码段不起作用? 函数foo(){ $(this.parent('li')。append('hello world'); }

Javascript 为什么这个简单的jQuery代码段不起作用? 函数foo(){ $(this.parent('li')。append('hello world'); },javascript,jquery,click,append,Javascript,Jquery,Click,Append,我正在尝试将字符串“hello world”附加到包含刚才单击的图像的。两个更改 [1] 在foo中添加一个参数 <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).pa

我正在尝试将字符串“hello world”附加到包含刚才单击的图像的
  • 两个更改

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

    <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>
    
    [2] 在onClick中传递foo中的参数

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

    无需连接onclick。使用jQuery只需执行以下操作

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

    检查处的工作示例,因为在
    foo
    函数
    中,此
    未定义,函数不知道哪个元素触发事件

    $('li').click(function(){
    $(this).append('hello world')
    });
    
    
    函数foo(elem)
    {
    $(elem).parent('li').append('asdf');
    }
    

  • 它不是将此功能添加到该页面中的每个li吗?要将其限制到特定的li集合,您需要指定UL id。例如:
    $('li','ulid')。单击(…)
    +1:获取jQuey事件处理的特定解决方案。添加jQuery而不使用它注册事件处理程序是浪费精力:)
    <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>