从一个大的HTML字符串创建一个jQuery对象 [英] Creating a jQuery object from a big HTML-string

查看:84
本文介绍了从一个大的HTML字符串创建一个jQuery对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个子节点的大HTML字符串。

是否可以使用此字符串构造 jQuery DOM对象?



我试过 $(string),但它只返回一个包含所有单个节点的数组。 / p>

尝试获取一个我可以使用.find()函数的元素。

解决方案

更新:



从jQuery 1.8开始,我们可以使用 $。parseHTML ,它将HTML字符串解析为一个DOM节点数组。例如:

  var dom_nodes = $($。parseHTML('< div>< input type =textvalue = val/>< / div>')); 

alert(dom_nodes.find('input')。val());

DEMO






  var string ='< div>< input type =textvalue =val/>< / div>'; 

$('< div />')。html(string).contents();

DEMO



这段代码发生了什么:




  • $('< div />')是假的< div> 在DOM中不存在

  • $('< div />')。html(string) append 字符串内假冒< div> 作为子女

  • .contents()将假冒< div> 的子元素作为jQuery对象进行检索



如果你想让 .find()工作,那么试试这个:



  var string ='< div>< input type =textvalue =val/>< / div>',
object = $('< div />')。html(string).contents();

alert(object.find('input')。val());

DEMO

I have a big HTML-string containing multiple child-nodes.

Is it possible to construct a jQuery DOM object using this string?

I've tried $(string) but it only returns an array containing all the individual nodes.

Imtrying to get an element which i can use the .find() function on.

解决方案

Update:

From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:

var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));

alert( dom_nodes.find('input').val() );

DEMO


var string = '<div><input type="text" value="val" /></div>';

$('<div/>').html(string).contents();

DEMO

What's happening in this code:

  • $('<div/>') is a fake <div> that does not exist in the DOM
  • $('<div/>').html(string) appends string within that fake <div> as children
  • .contents() retrieves the children of that fake <div> as a jQuery object

If you want to make .find() work then try this:

var string = '<div><input type="text" value="val" /></div>',
    object = $('<div/>').html(string).contents();

alert( object.find('input').val() );

DEMO

这篇关于从一个大的HTML字符串创建一个jQuery对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆