2013-02-18 61 views
1

我想一個文本行添加到圖像沒有ID或類我有一系列圖像,作爲jQuery的點擊圖片選擇下一個跨度無class和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"); 
}) 
}); 

我有點困惑,我應該如何使用未來這裏,也許我應該用找?我總是有一個img,然後是一個跨度。

+2

使用'$回調之內(這).next()。text(「your text goes here」)' – Archer 2013-02-18 19:15:47

+0

jQuery的'.next()'是一個函數,而不是一個屬性,所以你需要圓括號。 http://api.jquery.com/next/ – 2013-02-18 19:16:42

+0

使用您當前的代碼,只能爲所有這些代碼添加相同的文本。必須有一些方法來區分'img'? – nhahtdh 2013-02-18 19:17:16

回答

0

您的選擇器和方法不正確。爲了目標的跨度,可使用:

$(this).next('span') 

然後,改變文本的節點內,使用.text()代替.val()

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

(.VAL()用於輸入字段) 。

+0

這不起作用,因爲$('img')不會引用點擊的img。 – 2013-02-18 19:21:17

+0

@Wing Lian - 你是對的。編輯代碼以反映更正。 – 2013-02-18 19:35:06

1

你也應該考慮使用。對()以上。點擊(),但最重要的一條是$(本),這將參照點擊的對象

$(document).ready(function(){ 
    $("img").on('click', function(e){ 
     $(this).next('span').text("info inserted after clicking on the img next to span"); 
    }) 
});