开发者

JQuery with Element ID

I am trying to create a bit of jquery code to update an element but im having a problem. It wont update and I think its because of the element id?

Here is my JS Code:

<script type="text/javascript">
    $(document).ready(function()
    {
        $("#vote_button_" + $(this).attr('id')).click(function()
        { 
            $("div#vote_count").show().html('<h2>voting, please wait...</h2>');
        });
    });
</script>

And this is the HTML Code:

<div class="vote_container"> 
    <div class="vote_button" id="vote_button_31"><img src="/images/pi开发者_如何学运维cture_31.png"></div> 
    <div class="vote_count" id="vote_count">0</div> 
</div> 


You're telling it to use the ID of the document (I think).

You can surely just do:

    $("#vote_button_31").click(function()
    { 
        $("#vote_count").show().html('<h2>voting, please wait...</h2>');
    });

If you want the code to work on all vote buttons try this:

    $(".vote_button").click(function()
    { 
        $(this).siblings('.vote_count').show().html('<h2>voting, please wait...</h2>');
    });


$("#vote_button_" + $(this).attr('id')).click(function()...

The way you've called it, this has no context at all. Since you have a class on the div in question, why not use that instead?

$(".vote_button").click(function() {...

That will also work if you don't know the id in question when the page is loaded. If you're dynamically adding the divs then you might want to use live or delegate:

$(".vote_button").live("click", function() {...


Why you don't select the element directly:

<script type="text/javascript">
    $(document).ready(function()
    {
        $("div#vote_button_31").click(function()
        {
            $("div#vote_count").show().html('<h2>voting, please wait...</h2>');
        });
    });
</script>


YOu cannot do this. Instead try this:

<script type="text/javascript">
$(document).ready(function()
{
    $(".vote_button").click(function()
    { 
        $("div#vote_count").show().html('<h2>voting, please wait...</h2>');
    });
});

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜