javascript - 未捕获的 TypeError : textLocation[p]. find 不是一个函数

标签 javascript typeerror

我有一个<ul>未知号码 <li>里面的元素。 每<li>元素可以有或没有$('p.have')带有一些文本的元素。 我想收到来自每个 $('p.have') 的短信元素,如果没有 $('p.have')我们收到一个空字符串。 <ul> 的可能示例:

<ul>
        <li>
            <p class="have">Text from first</p>
        </li>
        <li>
            <p class="have">Text from second</p>
        </li>
        <li>
            <p class="notHave">Not our text</p>
        </li>
        <li>
            <p class="have">Text from fourth</p>
        </li>
        <li>
            <p class="have">Text from five</p>
        </li>
    </ul>

结果: '从第一个开始的文本', '第二个文本', ' ', '第四个文本'

我正在使用以下脚本:

var textLocation = $('ul li');
var  mytext = [];
function findText (){
    for (var p = 0 ; p < textLocation.length; p++) {
        if(textLocation[p].find('p.have')) {
            mytext.push($(this).text());
        } else { mytext.push(' ');}
    }


}

findText();
console.log(mytext);

但我收到以下错误

Uncaught TypeError: textLocation[p].find is not a function

谁能帮我解决这个问题

最佳答案

I want to receive a text from every $('p.have') elements and if there is no $('p.have') we have receive an empty string.

尝试这个简单的方法

var mytext = [];
$('ul li').each( function(){
  if ( $(this).find( "p.have" ).length > 0 )
  {
    mytext.push($(this).find( "p.have" ).text());
  }
  else
  {
    mytext.push($(this).find( "p.notHave" ).text());
  }
});

关于javascript - 未捕获的 TypeError : textLocation[p]. find 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43315484/

相关文章:

javascript - 为什么下划线(_)不被视为非单词字符?

javascript - 未捕获的类型错误 : Cannot read properties of undefined (reading 'remove' )

Python 错误 - python 测验中类型 'bool' 的对象没有 len()

javascript - Jasmine 测试以验证回调不会引发错误

python-3.x - 使用 discord.py 向指定 channel 发送消息时出错

python - 类型错误: '_io.TextIOWrapper' 对象不可订阅

javascript - Express.js - 监听关机

javascript - 引用错误 : date is not defined

javascript - 是否可以修改模拟 View 封装使用的属性名称

javascript - ReactJs 中的 ApexCharts 条形图垂直类别逻辑?