开发者

javascript variable to jQuery object

How can I take this javascript variable and

  1. convert it into jQuery object $(myFragment)

  2. 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>";


  1. To convert to jQuery object:

    $(myFragment);
    
  2. 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/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜