我有一个<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/