我有一個輸入字段,允許用戶輸入文本,包括<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,任何允許我從變量中剝離標籤的解決方案都是受歡迎的。
使用$('a')。attr('href',LINKHERE); – 2014-12-03 09:33:04
你想在replaceWith後得到#input值嗎? – 2014-12-03 09:33:26
是的replaceWith只能改變加載的值,而不是輸入的實際值(用戶可能想要進一步調整) – 2014-12-03 09:49:44