开发者

Settings Selector Dynamically in JQuery

I have a table whose values are being generated dynamically with PHP, including the id and name attributes (e.g. id="question_".

How can I set an element attribute with this in mind? For examp开发者_Go百科le, I have a div whose text will change after a successful ajax call, but the id is dynamic.

I have tried making the following test function, and calling it on an onclick event:

function approve(question_id)
{
    var div = 'suggestion_status_' + question_id;
    $('#div').html('test');
}

But that does not work. How can make the value of variable 'div' the selector?


The problem with your example is that div is a variable, not a string; so the following will work:

function approve(question_id)
{
    var div = 'suggestion_status_' + question_id;
    $('#' + div).html('test');
}

Or even:

function approve(question_id)
{
    $('#suggestion_status_' + question_id).html('test');
}

Another approach would be to utilize classes, and add a known class to your elements. Without seeing the full HTML, I can't provide a full example, but something like this would be the way to go:

$('.yourCommonClass').bind('click', function () {
    var that = this;

    jQuery.get('/accept.php', {
        id: this.id
    }, function (msg) {
        $(that).html('Accepted!');
    });
});

Bearing in mind that jQuery.get parameters are the target url, optional data attributes that are encoded in the request, and then a callback function.


you defined div as a variable then used it as a string try concatenating it instead

function approve(question_id)
{
    var div = 'suggestion_status_' + question_id;
    $('#'+ div).html('test');
}

or shorten like this

function approve(question_id)
{
    $('#suggestion_status_' + question_id).html('test');
}


$('#suggestion_status_' + question_id).html('test');


$('#suggestion_status_' + question_id)


I think you want this:

function approve(question_id)
{
    var div = 'suggestion_status_' + question_id;
    $('#'+div).html('test');
}


this. $('#suggestion_status_' + question_id).html('test'); 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜