I have a need to generate random id's for some buttons created on the page. I create the buttons using this jquery:
var btnId = 'delete-' + row.id;
$("<button/>", {
'id': btnId,
'html': $("<i></i>").addClass("ion-icon ion-btn ion-trash-a"),
'class': 'btn btn-primary btn-md'
}).append(' Delete')
The template for the button id's:
delete-$UUID
, where $UUID
is retrieved from a database.
This worked well, and after creating, I was able to even attach a click listener to each button using jquery:
$('button#' + btnId).click(function(e) { alert("Button clicked!"); }
The plot thickens
Now, I decided not to use the database row id, but instead generate a random string to use as the button id's, so I created this function:
function _randomString (min, max) {
var text = "";
var length = Math.floor(Math.random() * (max - min) + min);
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-abcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
, Then replaced the button id like this
var btnId = 'delete-' + _randomString(20, 30);
As you can see, the only thing different is that the $UUID
is replaced by the value of this function I created.
The climax
Now when I use jquery to add a click listener (the same jquery as above), the bind stopped working with jquery. No matter what happens, jquery does not seem to want to find and bind the click listener to the buttons when created with such an id.
At first, I thought this may be due to the function not generating random strings, but I went to the console and I took the generated id of one of the buttons, and when I did $('copied-button-id').length
, I got 1
. So obviously, jquery is able to find the button now, but not when it was created as was the case when I used the database row id to create the button id.
Even stranger is that when I remove that randomly generated string and replace it with a plain string like sdfsdfsd
, i.e. now all the buttons have the id delete-sdfsdfsd
, jquery has no problem finding and binding to the buttons.
Before anyone asks, I have also perused the acceptable ids for html elements, so this is not an issue. What are valid values for the id attribute in HTML?
Resolution
Here is where I need your help. I guess I'm either really tired or something, but can you look at my function and tell me what may be causing this issue. I've eliminated length issue, as I've been able to use ids of length in excess of 60 characters and they all worked. Is JQuery exhibiting undefined behavior by being able to find (or not) any of the buttons created in this way? Am I exhibiting undefined behaviour? What am I missing?
Any help is welcome!
Aucun commentaire:
Enregistrer un commentaire