簡體   English   中英

<a>使用jQuery</a>將<a>文本字符串</a>轉換<a>為dom元素</a>

[英]convert <a> text string to dom element with jQuery

如何將鏈接中的文本轉換為html元素?

我用$('a').text(); 它返回值,但我無法將元素添加到其中。

我已經試過了:

var someText = $('a').text();
var theElement = $('< p >' + someText + '< /p >');
someText.replaceWith(theElement);

我知道這可能會在鏈接內添加一個文本元素,這不是最佳實踐,但甚至行不通。

我真正需要的是刪除整個文本,並在將de link作為文本元素后立即將其重寫。

任何幫助表示贊賞。 謝謝

標記:

<li>
<a href="/"> <img src="image.png"> text to be converted to element </a>
</li>

我想要的是:

<li>
<a href="/"> <img src="image.png"></a>
<p> text to be converted to element </p>
</li>

由於someText是字符串,而不是jQuery元素,因此無法在其上調用.replaceWith() 嘗試這樣的事情:

var someLink = $('a');
var someText = someLink.text();
var theElement = $('<p>' + someText + '</p>'); // no spaces inside tags
someLink.replaceWith(theElement);

http://jsfiddle.net/0xxrL6zy/


更新由於您在問題中添加了新信息,因此可以滿足您的需求:

var someLink = $('a');
var someText = someLink.text();
var someImg = someLink.find('img');
var theElement = $('<p>' + someText + '</p>');
someLink.html(someImg).after(theElement);

http://jsfiddle.net/mblase75/mzbtr0qp/1/

http://jsfiddle.net/cvgbqb8b/2/

var anchor = $('li a');
anchor.after('<p>' + anchor.text() + '</p>')
    .contents()
    .filter(function(){
        return (this.nodeType == 3);
    })
    .remove();

在此處找到用於刪除文本的代碼https://stackoverflow.com/a/17852238/1415091

我建議:

// iterate over each of the <a> elements within <li> elements:
$('li a').each(function() {
  // create a <p> element, setting its text
  // to that of the 'this' element (the <a>):
  $('<p>', {
    'text': this.textContent
  // insert that created <p> after the current <a> element:
  }).insertAfter(this);

  // filtering the childNodes of the current <a>:
  $(this).contents().filter(function() {
    // keeping only those that are of nodeType === 3
    // and therefore are textNodes:
    return this.nodeType === 3;
  // removing those nodes:
  }).remove();
});

 $('li a').each(function() { $('<p>', { 'text': this.textContent }).insertAfter(this); $(this).contents().filter(function() { return this.nodeType === 3; }).remove(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li> <a href="/"> <img src="http://lorempixel.com/300/300/people" />text to be converted to element</a> </li> </ul> 

參考文獻:

使用.html()

var someText = 'Hey!';
$('#test').html('<p>' + someText + '</p>');

小提琴: http : //jsfiddle.net/howderek/3t3Lw75x/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM