我有以下HTML结构:
<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>
Run Code Online (Sandbox Code Playgroud)
除此之外,还有许多其他具有相同结构的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>
Run Code Online (Sandbox Code Playgroud)
现在,我有一个jQuery函数,它接受.message_topdiv 的ID,它应该使用.top_status属于它的div 的内容执行一个动作.但是,出于某种原因,在语法中它似乎不能识别.top_statusdiv 的ID .我知道我不能很好地解释这一点,但这里有一个小提琴,可以帮助你理解(代码和评论在那里):
$(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
});
});
Run Code Online (Sandbox Code Playgroud)
所以,如你所见,如果我.html()使用$("#status_7").html();它调用方法工作正常,但如果我调用它$("#"+status_id).html();(status_id为"status_7")它不起作用.这里发生了什么事?我已经多次使用类似的代码,从来没有遇到任何问题.