Dmi*_*sky 30 javascript jquery
我正在使用QUnit编写测试并使用$.ajax()HTML来从我在本地运行的开发站点获取一些测试:
add_elements = function(location, selector) {
$.ajax(location, {async: false}).done(function(data) {
stor.$els = $(selector, $.parseHTML(data));
stor.$els.appendTo($('body'));
})
}
Run Code Online (Sandbox Code Playgroud)
在某个位置使用此功能,我将以下内容data传递给我的.done()回调:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<div id="app-container" class="container-fluid">
<div class="page-header">
<h1>
<a href="/">Home</a>
<small>Text</small>
</h1>
</div>
<div id="hero-units" class="carousel-inner slide">
<div class="hero-unit home item active">
<h1>
Text text text
</h1>
<p>
More text!
</p>
<div id="app-nav">
<a id="lets-go" class="btn btn-primary btn-large nav-forward" href="/what-up/">
Let's go
</a>
</div>
</div>
</div>
</div>
<script src="/static/js/jquery.js"></script>
<script src="/static/js/underscore.js"></script>
<script src="/static/js/backbone.js"></script>
<script src="/static/js/bootstrap.js"></script>
<script src="/static/js/site-fiddle.js"></script>
<script src="/static/js/site.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果selector是#hero-units或者一切都有效.hero-unit,但如果是,则$(selector, $.parseHTML(data))返回任何selector内容#app-container!我想要一个元素的jQuery对象div#app-container.
这就是杀死我的原因:
$.parseHTML(data) 确实包含div#app-container元素.这只是$.parseHTML(data)[7].$('#app-container', $.parseHTML(data))是一个空阵列.$('div', $.parseHTML(data))包括div内部的所有内容div#app-container,但不包括div#app-container其本身.这里发生了什么?似乎正在发生的事情是$没有查看由$.parseHTML(data)or或者$($.parseHTML(data)))他们的孩子返回的任何顶级元素.
我怎样才能得到一个jQuery对象div#app-container从这个$.parseHTML(data)?
回答
该$(selector, $.parseHTML(data))式的查找使用$.find.因为我正在寻找这个jQuery对象中顶级元素,所以我应该使用$.filter.瞧.
Amy*_*Amy 31
您需要创建一个DOM元素来附加第一个结果,.parseHTML()以便在jQuery遍历并查找之前创建一个DOM树div#app-container.
var tempDom = $('<output>').append($.parseHTML(str));
var appContainer = $('#app-container', tempDom);
Run Code Online (Sandbox Code Playgroud)
我用你的例子让它工作:http://jsfiddle.net/gEYgZ/
该.parseHTML()函数似乎扼杀了<script>标签,所以我不得不删除它们.
PS.显然<output>不是真正的HTML标记,只是将它用于示例
jcu*_*bic 10
你可以试试这个:
$($.parseHTML('<div><span id="foo">hello</span></div>')).find('#foo');
Run Code Online (Sandbox Code Playgroud)
对于以<您开头的字符串,可以将代码简化为:
$('<div><span id="foo">hello</span></div>').find('#foo');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34607 次 |
| 最近记录: |