开发者

jquery add individual id

I try to give p elements different id's and then give every p a content. Here some of my previous work:

while(i<=10){开发者_如何学编程
    $.ajax({    
        url: "tabelle.html",
        success: function(data) {
            $('div').append("<p id='+i+'></p>");
            $('#"+i+"').html(data);
        },
        error: function(){
            alert('nein!');
        },  
    });     
    i++;
}
</script>
</head>
<body>
<div>
<p> </p>
</div>

But it isn´t working, can anybody help? You said I should be more specific, what isn´t working. The problem is, that it isn´t doing anything...


You are using single and double quotes next to each other instead of together.

$('div').append("<p id='+i+'></p>");

should be

$('div').append("<p id="+i+"></p>");

and

$('#"+i+"').html(data);

should be

$('#'+i).html(data);

Also, an elements id can't start with a number, so add some text in front:

$('#prefix_'+i).html(data);


The error function as the last parameter in your $.ajax() call is followed by a comma, but no other parameters are inserted after that. You may want to remove that comma.

Additionally, from what I understand, you are assigning numerical IDs. By definition this is not allowed. IDs must begin with a letter.

var id = 0;
for ( var x = 0; x < 10; x++ ){
    $.ajax({    
        url: "tabelle.html",
        success: function(data) {
            $('<p>').attr('id','p'+id).html(data).appendTo($('div'));
            id++;
        },
        error: function(){
            alert('nein!');
        } 
    });
}

I added "p" at the start of each ID.

To avoid the same ID problem, no need to fancy code stuff, just create a variable before the loop which will keep tracks of created IDs, and increment it each time a new element is created.


Apart from the concatenation problem, the problem is that each callback has a reference to the same i and at the time the callbacks are executed, the loop finished. All elements will have the ID 11.

You might think that each iteration waits until the Ajax call returns, but that is not the case. Ajax is asynchronous, the "surrounding" code does not wait for Ajax calls to finish (that's why you have to pass a callback).

The other issue is that JavaScript does not have block scope. You can create a new scope and "capture" the value of i be calling a function. Here is an example with an immediate (or self-involing) function:

while(i<=10) {
    (function(index) {
        $.ajax({    
            url: "tabelle.html",
            success: function(data) {
                $('<p />', {id: 'prefix' + index, html: data})
                 .appendTo('#divId');
            },
            error: function(){
                alert('nein!');
            }
        });
    }(i++));
}

Another solution would be to put the Ajax call in a named function and call it from the loop (passing the current index):

while(i<=10) {
    makeAjaxCall(i++);
}

In your special case, you don't even need to make the Ajax request in the loop. You are not sending any parameters to the server. In this case, you can iterate inside the success callback instead:

$.ajax({    
    url: "tabelle.html",
    success: function(data) {
        var $p = $("<p />", {html: data}),
            $div = $('#divId');
            i = 1; //?
        while(i<=10) {
            $div.append($p.clone().attr('id', 'prefix' + i);
        }
    },
    error: function(){
        alert('nein!');
    }
});

It is good to make as few requests as possible. Another option would be to send structured data as response (e.g. JSON [Wikipedia]), parse it and process it accordingly.

Things to consider:

  • In HTML4, IDs are not allowed to start with numbers. Although it most likely will work in all browsers, better prefix the ID with characters (it is valid in HTML5 though).

  • $('div') will select all divs in the page. That does not seem to be a problem in your specific example, but if your structure gets more complex, make sure you append the new element to only one element (otherwise you will have multiple elements with the same ID.

  • Trailing commas in object literals cause problems in IE.

  • You might have problems issuing so many requests at the same time. You could make the requests one by one by using jQuery's Deferred objects.


while(i<=10){
    $.ajax({    
        url: "tabelle.html",
        success: function(data) {
            $('div').append("<p id='element" + i + "'></p>");
            $('#'+i).html(data);
        },
        error: function(){
            alert('nein!');
        } 
    });     
    i++;
}

EDIT: It's also worth mentioning... don't make ajax requests in a loop. Make one request which returns all your required data and then loop over the result instead.


First things first, you've mixed up your quotes in this line:

$('div').append("<p id='+i+'></p>");

That should be

$('div').append("<p id='" +i+ "'></p>");

But, stop! id's cannot begin with a numeric, so change this to

$('div').append("<p id='something" +i+ "'></p>");

where "something" must start with a character or underscore.

Then change the other line to

$('#something' +i).html(data);


Your string concatenation looks wrong. Your start with single quotes and use double to concat.

Use

"<p id="+ i +"></p>"

OR even better

'<p id="'+ i +'"></p>'


There are multiple issues with your code.

First, make sure HTML correct (you have given us only a snippet of it). Second, make sure jQuery is loaded when the script is called.

But the main issue is with incorrect quotes:

$('div').append("<p id='+i+'></p>");

should be replaced by

$('div').append('<p id="' + i + '"></p>');

and

$('#"+i+"').html(data);

should be replaced by

$('#' + i).html(data);

Let us know if this helped - there may be additional issues.

EDIT:

As others mentioned, your id is incorrect (should not start with a number, maybe add "p-" prefix before i), also the trailing comma is not good - you should remove it. Additionally you can use for instead of while and increments; plus you should not use i as global variable. The resulting JS code would look like this:

for(var i=1; i<=10; i++){
    $.ajax({    
        url: 'tabelle.html',
        success: function(data) {
            $('div').append('<p id="p-' + i + '"></p>');
            $('#p-' + i).html(data);
        },
        error: function(){
            alert('nein!');
        } 
    });
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜