开发者

JQuery with Element ID

开发者 https://www.devze.com 2023-04-04 19:14 出处:网络
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?

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

精彩评论

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