Javascript 如何使用 jQuery 从字符串中获取 HTML 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3754092/
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
How to get a HTML element from a string with jQuery
提问by Raphael
I'm looking for a way to get a HTML element from a string that contains HTML. Is it possible to use a jQuery selector to do this?
我正在寻找一种从包含 HTML 的字符串中获取 HTML 元素的方法。是否可以使用 jQuery 选择器来做到这一点?
I have a Javascript function that gets an entire page from the server, but I only need one element from that page.
我有一个 Javascript 函数可以从服务器获取整个页面,但我只需要该页面中的一个元素。
回答by Guffa
Yes, you can turn the string into elements, and select elements from it. Example:
是的,您可以将字符串转换为元素,并从中选择元素。例子:
var elements = $(theHtmlString);
var found = $('.FindMe', elements);
回答by KingErroneous
Just wrap the html text in the $ function. Like
只需将 html 文本包装在 $ 函数中。喜欢
$("<div>I want this element</div>")
回答by Peter Ajtai
If you are loading a page dynamically from a server then you can target just one element from the loaded page using the following form with .load()
如果您从服务器动态加载页面,那么您可以使用以下表单从加载的页面中只定位一个元素 .load()
$(selectorWhereToShowNewData).load('pagePath selectorForElementFromNewData');
For example:
例如:
$('#result').load('ajax/test.html #container');
Where:#result
is where the loaded page part will be displayed on the current pageajax/test.html
is the URL to which the server request is sent#container
is the element on the response page you want to display. Only that will be loaded into the element #result
. The rest of the response page will not be displayed.
其中:#result
加载的页面部分将在当前页面上显示ajax/test.html
的位置 服务器请求发送到的 URL 是#container
您要显示的响应页面上的元素。只有那个会被加载到元素中#result
。响应页面的其余部分将不会显示。
回答by jayson.centeno
Just use $.filter
只需使用 $.filter
var html = "<div><span class='im-here'></span></div>"
var found = $(html).filter(".im-here")
回答by hiFI
You can use $.find
您可以使用 $.find
$(document).ready(function() {
var htmlVal = "<div><span class='im-here'>Span Value</span></div>";
var spanElement = $(htmlVal).find("span");
var spanVal = spanElement.text();
alert(spanVal);
});