在变量中替换

时间:2014-12-03 09:29:18

标签: jquery

我有一个输入字段,允许用户输入文本,包括<a href>个链接。我想要做的是使用这个值呈现为html和纯文本,只显示每个<a href>标记的内容。

我发现我可以使用下面的代码段来替换<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(); });
});

以上示例有效,但我真正想做的是将输出平面和输出替换为变量,以便稍后我可以将它们发送到模板。但是,如果不输出到页面,我无法弄清楚如何进行替换。

我不仅限于使用replaceWith,任何允许我从变量中剥离标记的解决方案都是受欢迎的。

1 个答案:

答案 0 :(得分: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()的方法可以帮助您从其父级中取出一个元素