selection error in jquery with dynamic elements
First of all thanks for reading. I have a problem with jQuer开发者_如何学Pythony. I am trying to get some data with AJAX and put the result on page with dynamically created div. This works perfect. The problem occurs when I try to select the created div and do something with it
$('.myNewDiv').css('border', '2px solid #000080');
It gives me error in jQuery library
In Chrome debugger it is "Uncaught TypeError: Cannot read property 'slice' of undefined" on line 2234
And in Firebug under firefox "Array.prototype is undefined Line 3324"
I have no idea what is the problem so i'd be grateful for any information
The whole function code:
function AddNextDiv(number) {
var url2 = '<%= ResolveUrl("~/Translate/GetLineDetails") %>';
$.getJSON(url2, { textLineID: LinesIDs[number], TranslatedSubsID: '<%= Html.Encode(Model.OutputSubs.SubsID) %>' }, function (result) {
if (result == "Already in Database") return false;
var myObject1 = JSON.parse(result);
$("#MainField").append("<div class=\"TextLineDiv\">This is line number " + myObject1.LineNumber + " of 423<br/>" + myObject1.TextValue + "<br/><input id=\"TranslationBox" + myObject1.LineNumber + "\" class=\"translationTextBox\" type=\"text\" size=\"20\" /><br/><div id=\"CheckBoxDiv" + myObject1.LineNumber + "\"><input name=\"" + myObject1.LineNumber + "\" class=\"addCheckBox\" onchange=\"HideDiv(this)\" type=\"checkbox\" /><br/><div class=\"NumberDiv\" title=\"" + myObject1.LineNumber + "\" onmouseover=\"CallRefresh(this)\" > This line was translated <div id=\"Translated" + myObject1.LineNumber + "\">" + myObject1.TimesTranslated + "</div> times.</div><br/><br/></div></div>");
$("div#MainField div.TextLineDiv").css('border', '2px solid #000080');
return true;
});
}
`
You can't select things that aren't added to the document yet. If you can restructure your code so that the div can be caught into a variable it would be easy. Otherwise you need to do something like add it to a hidden element then select it. (yuk!)
I suggest using jQuery's DOM tools rather than building everything as a big string of html.
精彩评论