开发者

Problem using JQuery live to get img id value

I was hoping someone could tell me what I was doing wrong in the code that follows. I have an existing page that uses jQuery to load new content into one of the page divs: div1 without refreshing (working fine). The new content that is loaded has a help icon image with the following attributes: class="helpicon" id="1".

What I am trying to do is to use jQuery to take the id value from the help icon image, pass it to the php/database connection file help.php which gets the correct content from the database and populates another div id="content_help_main" on the original page, again without refreshing the entire page. I am using the php/database connection file help.php on another page that uses the original content of div1, which also has a help icon image to populate the div id="help_content_main", so I think the issue is just my use of the jQuery live method, which seems to be wrong. Any help is appreciated!

Here is my jQuery script:

$(function() {
$('.helpicon').live('click', function() {

var data = "id=" + $img.attr("id");
$.ajax({
    type: "POST",
    url: "help.php",
    data: data,
    success: function(output) {
 开发者_JAVA技巧           $('#content_help_main').html(output).show();
    }
        });
});
})


Try replacing

var data = "id=" + $img.attr("id");

with

var data = "id=" + $(this).attr("id")


It looks like your selector for the img id is wrong.

var data="id="+$img.attr("id");

should be

var data="id="+$(this).attr("id");

$(this) is the helpicon you're clicking on, that way it'll work if you have a bundle of these throughout your site.

Having $img is throwing an error, as you always need to enclose your selector (in this case, img) inside the $ sign, parenthesis, and quotes -- $('').

The problem with just using $('img') is that it will grab the id from the first image it hits on your site, which may well be something other than the helpicon. Using $(this) ties it to the item being clicked (which will always be the help icon!).

edit: AHHH, dave beat me to it. kudos.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜