gpt4 book ai didi

Javascript:无法从 html 标签中提取 .text()

转载 作者:行者123 更新时间:2023-12-03 07:22:08 24 4
gpt4 key购买 nike

我正在编辑此内容以根据 georg 的答案添加我的解决方案。解决方案在底部。

我正在尝试使用给定标签获取包含的文本。

var substring = txt.find(tag).eq(i).text(); 

示例数据:

变量tag包含“h1”。

变量txt包含“

一条。

两条鱼。红鱼。蓝鱼。

”。

期望:

子字符串 ==“鱼”

结果:

子字符串 == null

代码:

this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;

var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );

txt = jQuery(txt);

for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_tagToText(tag);
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}

return result;
} catch(e) {
console.log(e);
return false;
}
}

解决方案:

    this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;

var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );

for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_tagToText(tag);
var substring = jQuery('<div>').html(txt).find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}

return result;
} catch(e) {
console.log(e);
return false;
}
}

最佳答案

要使用find,您必须将 html 放入容器中:

txt = "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>";

result = $('<div>').html(txt).find('h1').text()

alert(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于Javascript:无法从 html 标签中提取 .text(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36172050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com