javascript variable to jQuery object
How can I take this javascript variable and
convert it into jQuery object $(myFragment)
change the id attribute from "fragment" to "fragment1" ?
myFragment = "\ <div id='fragment'>\ <input type='hidden' id='preBeginDtlFields' name='BeginDtlFields'\ value='' />\ 开发者_开发技巧<input type='hidden' id='preGroup' name='GRP' value='' />\ </div>";
To convert to jQuery object:
$(myFragment);
To change the id:
$(myFragment).attr('id', 'fragment1');
To convert the string to HTML element pass it to jQuery function as parameter and it will return you a html element wrapped as a jQuery object. Then you can use all the regular jQuery functions to change the element.
Try this:
var myFragment = "\
<div id='fragment'>\
<input type='hidden' id='preBeginDtlFields' name='BeginDtlFields'\
value='' />\
<input type='hidden' id='preGroup' name='GRP' value='' />\
</div>";
var $myFragment = $(myFragment).appendTo("body");
$myFragment.attr("id", "new-id");
$("#new-id").text("It works!!!");
Working example: http://jsfiddle.net/xhC7D/
精彩评论