Testing for existing element with jQuery's .length doesn't see newly created elements
I'm trying to create a copy/paste system for a HTML table using jQuery and a context menu plugin and I'm trying to uniquely name all of the newly created rows. So I have a function that is cloning the selected row and inserting the new row above:
function cloneAbove(TR) {
var newRow = $(TR).clone();
var lastID = $(TR).attr('id');
var newID = Number(lastID.substring(3))-0.1;
//See if that row开发者_C百科 already exists:
if($('#tr_'+newID).length){
alert('#tr_'+newID+' Exists');
//If it does exist, we divide the newID by 10 until we find one that doesn't:
var i = 0;
while(i < 1){
newID = newID/10;
if($('#tr_'+newID).length > 0){
i = 1;
}
}
}
$(newRow).attr('id','tr_'+newID);
$(TR).before(newRow);
$(".target").contextmenu(option);
}
First it clones the selected row (ie: '#tr_1'), subtracts 0.1 for the new row's id (ie: '#tr_0.9'), then it is supposed to check to see if that id already exists - this is where my problem is - if it exists it enters a loop to divide by 10 until it finds a id that doesn't.
Here is a sample of the table:
<table id="table" border=1>
<tr class="target" id="tr_1" oncontextmenu="context('tr1')">
<td id="tr_1_1">Row1</td>
<td id="tr_1_2">Row1</td>
</tr>
<tr class="target" id="tr_2" oncontextmenu="context('tr2')">
<td id="tr_2_1">Row2</td>
<td id="tr_2_2">Row2</td>
</tr>
</table>
The .length works for the 'hard coded' elements as they exist when the page loads, but it won't detect any of the newly created elements. Any suggestions?
You're building "id" values that are going to confuse jQuery. The selector "#tr_0.9" means, "find the element with id 'tr_0' and class '9'", not "find the element with id 'tr_0.9'".
Setting aside the fact that that strikes me as a pretty weird way to construct "id" values, you may be able to make it work by "quoting" the "." characters:
if ($(('#tr_' + newId).replace(/\./g, "\\.")).length) {
// ... found a duplicate ...
What that does is substitute "." for "." in the constructed trial "id" value. You only want to do that, of course, when looking for the elements via a jQuery selector; you don't want the actual "id" value to have backslashes in it.
Alternatively, you could replace the "." characters with "_" or something.
You need to think about how your jQuery selector is getting parsed. When you add a new row your new row's id is set to a decimal digit (ie '0.9'). But when using the jQuery selector
$('#tr_0.9')
you are saying:
get the an element with id of 'tr_0' and a class of '9'.
The dot operator is the notation for a class selector. Try using whole number values instead of decimal ones.
Edit: I was too slow!
精彩评论