我有以下HTML結構:「對飛」創建元素ID不jQuery的
<div class='message_top' id='top_7' style='cursor:pointer;'>
<div class='top_ime'>From: official</div>
<div class='top_status' id='status_7'>
<img src='images/message_new.png' height='26' title='New message' />
</div>
</div>
除此之外,還有很多相同結構的其他的DIV的,但用不同的ID號,例如:
<div class='message_top' id='top_15' style='cursor:pointer;'>
<div class='top_ime'>From: official</div>
<div class='top_status' id='status_15'>
<img src='images/message_new.png' height='26' title='New message' />
</div>
</div>
現在,我有一個jQuery函數,它接受一個.message_top
div的ID和它應該執行使用.top_status
DIV屬於它的內容的動作。但是,出於某種原因,在語法上,它似乎不能識別.top_status
div的ID。我知道我n要解釋這很好,但這裏有一個小提琴,這將有助於你理解(代碼和註釋是否有):
$(function() {
$('.message_top').click(function(){
var id = this.id;
status_id = id.replace("top","status");
status = $("#"+status_id).html();
alert(status_id+" "+status); //status variable is empty, but...
status2 = $("#status_7").html();
alert(status2); //status2 has the expected value
});
});
所以,你看,如果我叫.html()
方法使用$("#status_7").html();
它工作正常,但如果我用$("#"+status_id).html();
(status_id爲「status_7」)調用它不起作用。這裏發生了什麼事?我多次使用類似的代碼,從來沒有任何問題。
看來,如果你在適當的位置加載你的代碼工作正常(提示:在文檔準備或負載)
我今天這個剛纔已經回答。 http://jsfiddle.net/j08691/gMy2f/4/ – j08691 2013-04-11 15:27:36
@ j08691我剛剛嘗試了你的代碼,它的失敗方式與我的方式一樣(至少在Firefox中) - 我很確定我的加載方式是精細。 – jovan 2013-04-11 15:29:03
代碼在firefox 19.0.2中工作得很好,也許瀏覽器兼容性問題? – gbtimmon 2013-04-11 15:29:11