jQuery element.text()错误“不是函数";当我使用elements数组时 [英] Jquery element.text() error "is not a function" when I use elements array

查看:185
本文介绍了jQuery element.text()错误“不是函数";当我使用elements数组时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个XML文件,其中有一些p标签,并且我想获取每个元素文本"element.find()".但是我收到了这个错误".text不是函数".

I am reading a XML file in which I have some p tags, and I want to to get each element text "element.find()". But I got this error ".text is not a function".

这是我使用的代码:

            $.ajax({
                type: 'GET',
                url: YQLurl,
                data: {
                    key: "value"
                },
                dataType: "xml",
                success: function (reciviedXml){

                    for(var i = 0 ; i < $(reciviedXml).find('p').length;i++)
                    {
                      var paragraph= $(reciviedXml).find('p')[i].text(); 
                    }   
                });

我认为我的数组不是元素数组,或者至少jquery无法将其理解为元素列表,我该怎么办?

I think my array is not an array of elements, or at least jquery can not unserestand it as elements list, what should I do?

推荐答案

这显然将不起作用,因为$(reciviedXml).find('p')[i]将返回本机DOM Element,并且Element上没有text方法的界面.如果您执行$(reciviedXml).find('p')[i].textContent;,您的代码应该可以工作,尽管这样做效率极低.

That will obviously won't work as $(reciviedXml).find('p')[i] will return a native DOM Element and there is no text method on the Element's interface. Your code should work if you do $(reciviedXml).find('p')[i].textContent; although it would be extremely inefficient.

这是一种更好的方法:

$(reciviedXml).find('p').each(function () {
    var paragraph = $(this).text();

    //do something useful with paragraph
    console.log(paragraph);
});

我只想要第3个标签文本,它会给我错误

I just want the 3rd tag text it gives me the error

您也可以执行$(reciviedXml).find('p:nth-child(3)').text()直接获取第三段的文本.

You can also do $(reciviedXml).find('p:nth-child(3)').text() to get the text of the third paragraph directly.

您可能也根本不使用jQuery:

You may also not use jQuery at all:

var htmlString = '<p>1</p><p>2</p><p>3</p>';

var text = new DOMParser()
    .parseFromString(htmlString, 'text/html')
    .querySelector('p:nth-child(3)')
    .textContent;

alert(text);

这篇关于jQuery element.text()错误“不是函数";当我使用elements数组时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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