开发者

Jquery problem .click .each

Hi can you help me with this JQUERY based code?

<script>
$(function() {      
    $("#chatIM").each(function() { 
        $(this).click(function() { 
            $.post("chatController.php", { action:"getChat", 
                               user:"<?php echo $loggedInUser->display_username; ?>", 
                               other: $(this).attr("title"), 
                               type: "<?php echo USERTYPE; ?>"}, 
            function(data) { 
                $("#chatUsers").empty(); 
                $(document.createElement("div")).attr({id: 'chatbox'}).html(data).prependTo("body"); 
            }); 
        });
    }); 
});
</script>

<a id="chatIM" title="gowthami">CHAT 开发者_StackOverflow社区ME</a>
<a id="chatIM" title="vaisakhi">CHAT ME</a>

I am not sure where is the problem but when I press first of those buttons it works but for the second it doesn't work (there will be a lot of A tags with the same ID so the code must work to each one. Perhaps its a wrong syntax at .each .click or somewhere else. Can you help me whith that?


It will cause problems if you assign the same id to multiple elements, ids should be unique in a document. You could use classes instead -

<a class="chatIM" title="gowthami">CHAT ME</a>
<a class="chatIM" title="vaisakhi">CHAT ME</a>

and your jQuery would change to -

$(".chatIM").each(function ...


You shouldn't have more than one element on a page with the same ID. Change the id to a class:

<script>
    $(function(){       
    $(".chatIM").each(function(){ 
$(this).click(function(){ 
$.post("chatController.php", {action:"getChat", user:"<?php echo $loggedInUser->display_username; ?>", other: $(this).attr("title"), type: "<?php echo USERTYPE; ?>"}, 
function(data){ 
$("#chatUsers").empty(); 
$(document.createElement("div")).attr({id: 'chatbox'}).html(data).prependTo("body"); }); });
}); 
});
</script>    
               <a class="chatIM" title="gowthami">CHAT ME</a>
               <a class="chatIM" title="vaisakhi">CHAT ME</a>


The id field should be unique across the document. Try adding a class attribute like this:

<a class="chatIM" title="gowthami">CHAT ME</a>

And change the jQuery code to this:

$(".chatIM").each(function(){ 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜