简体   繁体   English

如何使用jQuery或Prototype获取位于STRING(不是DOM)中的HTML标签的内部HTML值?

[英]how can I get the inner HTML value of an HTML tag that is IN A STRING (not DOM) using jQuery or Prototype?

I have HTML in a string returned by an ajax call. 我在ajax调用返回的字符串中包含HTML。 I would like to get the value of an element like I would with a normal selector: $('#my_div') , not by regex. $('#my_div')使用普通选择器那样获取元素的值: $('#my_div') ,而不是通过正则表达式。

Unfortunately I don't know how to do this since it's in a string... 不幸的是,因为它是字符串,所以我不知道该怎么做。

Can anyone help? 有人可以帮忙吗?

Try: 尝试:

$(htmlString).html()

$(htmlString) will create a DocumentFragment of the String what will be accessible by jQuery. $(htmlString)将创建String的DocumentFragment,jQuery可以访问它。

Use find() to access specific elements inside this fragment: 使用find()访问此片段内的特定元素:

$(htmlString).find('someselector').html()

Will do it like that : 会那样做:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: '/echo/html/',
        dataType: "html",
        data: {
            html: "<span id='foo'>test</span><br/><span>Test2</span>",
            delay: 1
        },
        success: function(data, textStatus, jqXHR) {
            $('#result').append($(data));

            // use $("#result selector") here, for example:
            alert($("#result #foo").text());
        }
    });
});

with a div#result in the HTML doc HTML文档中的div#result

see http://jsfiddle.net/Regisc/tzHsb/1/ 参见http://jsfiddle.net/Regisc/tzHsb/1/

Be aware that evaluating the string from the ajax call can be dangerous because there can be a script in the response. 请注意,从ajax调用中评估字符串可能很危险,因为响应中可能包含脚本。

Took me a while to figure this out, but I had to add a wrapper to my html to get this to work, otherwise jQuery returns an array of elements, and looks inside each. 花了我一段时间才能弄清楚这一点,但是我必须在html中添加包装器才能使其正常工作,否则jQuery返回一个元素数组,并在每个元素内部进行查找。

This worked for me: 这对我有用:

jQuery("<div>" + response.responseText + "</div>").find('#response_code').html()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM