2016-04-28 5 views
1

私はそこにリンクが入れ子になっている段落があります。ネストされたリンクを打たずにテキストを切り捨てます。

<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p> 

私は、段落テキストを切り捨て、<a></a>タグには何も影響を与えることなく、省略記号でそれを終了する必要があります。

私は$(p).text($(p).text().substring(0,n)+'...');を使用してテキストの切り捨てを行うことができますが、もちろん、段落をつかんで$(p).text()を使用すると、リンクが含まれていて、それを駄目にするでしょう。

</a>に影響することなく、切り捨てられたバージョンである<p>のテキストを取得して置き換える方法はありますか。好ましくは、正規表現を使用したり、リンクをクローンして再追加したりする必要はありませんか?

+1

あなたはアンカータグをクリックすることでこれを行うにはしたいですか? またはページが読み込まれますか? –

+0

@SunilKumarこれはページロード時に発生します – DasBeasto

+0

見てください:http://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without-changing-its-child-elements –

答えて

2

nodeTypeを使用してこのようなことを行うことができます。次に、textContentプロパティを使用して値を変更することができます。テキストノードの場合

、NodeTypeプロパティは、スクリプトを次のよう試すことができます。3.

alert($('p').contents().filter(function() { 
 
    return this.nodeType == 3; 
 
})[0].textContent); 
 

 
//set new value 
 
$('p').contents().filter(function() { 
 
    return this.nodeType == 3; 
 
})[0].textContent = 'New text ';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p>

+0

はよさそうですね! 'this.nodeType == 3;とは何かを説明してもらえますか? –

+0

@Reddy私はちょうどしました。 – RRK

+0

は意味があります+1。 –

1

$(function() { 
 
    
 
    var x = $("p").contents().get(0).nodeValue; // This will grab the text ignoring the other nodes: 
 

 
    $("p").html(x.substring(0, 5) + '...' + $("p").find("a").wrap("<p>").parent().html()); // Setting x and appending the <a> html 
 

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

 
<p>Lorem ipsum blah blah blah <a href="link">Read More</a> 
 
</p>

0

を返します。

$(document).ready(function() { 
 
     var hrefTag = $('a').attr('href'); 
 
     $('p').html('<a href="' + hrefTag + '">Read More</a>'); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Lorem ipsum blah blah blah <a href="link">Read More</a></p>

関連する問題