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

时间:2016-03-23 07:25:43

标签: javascript jquery html

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

我正在尝试使用。

从给定标签中获取所附文本
var substring = txt.find(tag).eq(i).text(); 

示例数据:

变量标记包含" h1"。

变量 txt 保存"< p>一个。< / p>< h1> fish< / h1>< p>两条鱼。红鱼。蓝鱼。< / p>"。

期望:

subString ==" fish"

结果:

subString == 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;
        }
    }

3 个答案:

答案 0 :(得分:1)

要使用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>

答案 1 :(得分:0)

我就是这样做的:

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


var result = txt.match(new RegExp("<"+tag+">(.*)</"+tag+">"));
console.log(result[1]);

alert(result[1]);

Here is the JSFiddle demo

使用通过正则表达式提供的标记u过滤字符串,标记之间的文本显示为消息。

答案 2 :(得分:0)

我尝试过以类似的方式做事并且能够做得很好。

请参阅demo

以下代码:

HTML:

Line1
Line2

Line3

JS:

 <div class="test">Test div 1</div>
 <div class="test">Test div 2</div>
 <div class="test">Test div 3</div>


<div class="newDiv"><p>New Div</p></div>