Почему этот простой фрагмент jQuery не работает? - PullRequest
2 голосов
/ 21 февраля 2011
<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" к <li>, которая содержит изображение, на которое только что щелкнули.

Ответы [ 3 ]

3 голосов
/ 21 февраля 2011

не нужно прикреплять на клик. С помощью jQuery просто сделайте

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

Проверьте рабочий пример на http://jsfiddle.net/tFr5y/

2 голосов
/ 21 февраля 2011

Поскольку в 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>
1 голос
/ 21 февраля 2011

Два изменения

[1] Добавить параметр в foo

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

[2] передать параметр в foo в onClick

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