javascript 变量到 jQuery 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7005437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript variable to jQuery object
提问by bob
How can I take this javascript variable and
我怎样才能使用这个 javascript 变量和
convert it into jQuery object $(myFragment)
change the id attribute from "fragment" to "fragment1" ?
将其转换为 jQuery 对象 $(myFragment)
将 id 属性从“fragment”更改为“fragment1”?
myFragment = "\ <div id='fragment'>\ <input type='hidden' id='preBeginDtlFields' name='BeginDtlFields'\ value='' />\ <input type='hidden' id='preGroup' name='GRP' value='' />\ </div>";
myFragment = "\ <div id='fragment'>\ <input type='hidden' id='preBeginDtlFields' name='BeginDtlFields'\ value='' />\ <input type='hidden' id='preGroup' name='GRP' value='' />\ </div>";
回答by bfavaretto
To convert to jQuery object:
$(myFragment);
To change the id:
$(myFragment).attr('id', 'fragment1');
转换为 jQuery 对象:
$(myFragment);
要更改 ID:
$(myFragment).attr('id', 'fragment1');
回答by Chandu
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.
要将字符串转换为 HTML 元素,请将其作为参数传递给 jQuery 函数,它将返回一个包装为 jQuery 对象的 html 元素。然后您可以使用所有常规 jQuery 函数来更改元素。
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/
工作示例:http: //jsfiddle.net/xhC7D/