2014-12-03 33 views
0

我有一個輸入字段,允許用戶輸入文本,包括<a href>鏈接。然後我想要做的就是使用這個值作爲html和純文本格式,只顯示每個<a href>標籤的內容。replaceWith在變量

我發現我可以使用下面的代碼片段來替換<a href>標籤的內容。

$("a").replaceWith(function() { return $(this).contents(); }).val(); 

HTML示例:

input: <input type="text" id="input"/><br /> 
plain output: <div id="outputplain"></div><br /> 
replaced output: <div id="outputreplaced"></div><br /> 

例JS:

// simulate user input 
$('#input').val('<a href="http://stackoverflow.com">me</a> and <a href="http://stackexchange.com">you</a>'); 

// try to render 
$('#input').click(function() { 
    var input = $(this).val(); 

    // html rendered 
    $('#outputplain').html(input); 

    // plain rendered 
    $('#outputreplaced').html(input); 
    $("#outputreplaced a").replaceWith(function() { return $(this).contents(); }); 
}); 

在上面的例子中工作,但我真的很想做的是保持outputplain和outputreplaced作爲變量,這樣我可以稍後將它們發送到模板。但是我可以不知道如何在不輸出到頁面的情況下進行更換。

我不限於使用replaceWith,任何允許我從變量中剝離標籤的解決方案都是受歡迎的。

+0

使用$('a')。attr('href',LINKHERE); – 2014-12-03 09:33:04

+0

你想在replaceWith後得到#input值嗎? – 2014-12-03 09:33:26

+0

是的replaceWith只能改變加載的值,而不是輸入的實際值(用戶可能想要進一步調整) – 2014-12-03 09:49:44

回答

1

您可以使用一個臨時jQuery對象(DOM),如

// simulate user input 
 
$('#input').val('<a href="http://stackoverflow.com">me</a> and <a href="http://stackexchange.com">you</a>'); 
 

 
// try to render 
 
$('#input').click(function() { 
 
    var input = $(this).val(); 
 

 
    // html rendered 
 
    $('#outputplain').text(input); 
 

 
    var $tmp = $('<div />', { 
 
    html: input 
 
    }); 
 
    $tmp.find('a').contents().unwrap(); 
 

 
    var replaced = $tmp.html(); 
 
    // plain rendered 
 
    $('#outputreplaced').text(replaced); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="button" id="input" /> 
 
<div id="outputplain"></div> 
 
<div id="outputreplaced"></div>

此外,你可以看到有一個叫.unwrap()方法,幫助您採取元素讓開父母

+0

$ tmp定義的末尾沒有分號(這個stackoverflow不會讓我修復)。否則,這完美的作品。非常感謝! – 2014-12-03 09:47:43