1

我正在尝试向没有 id 或类的图像添加文本行我有一系列图像,例如

  <img src="../img/star.png"  /><span>no text here until left img is clicked</span>

  <img src="../img/someotherpicture.png"  /><span>no text here until left img is clicked</span>

  <img src="../img/anotherpicture.png"  /><span>no text here until left img is clicked</span>

对于 jquery 我有

$(document).ready(function(){
$("img").click(function(){  
$("img").next.$("span").val("info inserted after clicking on the img next to spa");
})
});

我有点困惑我应该如何在这里使用 next ,或者我应该使用 find ?我总是有一个 img 后跟一个 span。

4

2 回答 2

2

您还应该考虑使用 .on() 而不是 .click(),但最重要的部分是回调中的 $(this),它将引用单击的对象

$(document).ready(function(){
     $("img").on('click', function(e){  
        $(this).next('span').text("info inserted after clicking on the img next to span");
    })
});
于 2013-02-18T19:17:53.893 回答
0

您的选择器和方法不正确。为了定位跨度,请使用:

$(this).next('span')

然后,要更改节点内的文本,请使用.text()而不是.val()

 $(this).next('span').text('info inserted after clicking on the img next to spa');

(.val() 用于输入字段)。

于 2013-02-18T19:17:01.707 回答