jQuery - 加载文本区域,为每个 href 添加后缀并显示结果

jQuery - loading textarea, adding suffix to every href and displaying the result

我正在努力让 jQuery 发挥作用。它需要 select 来自文本区域的一些 html 代码,向其中的 every href 添加一个后缀,然后在另一个中显示生成的 html 代码文本区域。我不希望它渲染 HTML,只显示代码。

这是我必须...

$('#apply').click(function() {
    var a = $('#a').val();
    var b = $('#b').val();
    var c = $('#c').val();

    var query_string = '?a=' + a + '&b=' + b + '&c=' + c;

    var input_html = $("#input_html").val();

        $(input_html + ' a').each(function() {
            var href = $(this).attr('href');

            if (href) {
                href += (href.match(/\?/) ? '&' : '?') + query_string;
                $(this).attr('href', href);
            }
        });

    $("#output_html").val(input_html);
});

它应该很简单,我想我已经很接近了,但我完全不知道为什么它不起作用。有人想知道我哪里出错了吗?

2016 年 4 月 11 日更新

感谢您的回答,但它会破坏嵌套代码,例如试试这个...

<table><tr><td><a href="foo-bar"><img src="image.jpg"></a></td></tr></table>
<a href="foo-bar"><img src="image.jpg"></a>

第一个 link 没有查询字符串,第二个有?

您的 input_html var 是一个文本字符串 - 您需要将其解析为 DOM 个对象,然后才能检查锚标记并使用它们的 hrefs。

完成后,您可以修改它们,然后将它们转回 HTML 以供您输出。

下面的示例处理了几种不同的情况 - 尽管当锚点具有空白 href 时会出现奇怪的行为

$('#apply').click(function() {
    var a = $('#a').val();
    var b = $('#b').val();
    var c = $('#c').val();

    // don't need the ? here, we add it later
    var query_string = 'a=' + a + '&b=' + b + '&c=' + c;

    var input_html = $("#input_html").val();
    
    // parse string into HTML DOM objects
    var html_dom = $.parseHTML( input_html );
 
    // create a new var to store our new output
   var output_html = '';
    
    // loop over DOM objects, check for anchor tags
    $.each( html_dom, function( i, el ) {

      if( el.nodeName === 'A' ) {
      
          // if we have an anchor, get it's href
          var href = el.href;

          // if it's not blank, append query
          if ( href != '' ) {
            el.href += (href.match(/\?/) ? '&' : '?') + query_string;
          }
      }
      
      // append the element as html to the output string
      // here we make a div $(<div/>)
      // inject the element ,append($(el))
      // then ask jQuery to give the contents as HTML .html()
      output_html += $('<div/>').append($(el)).html();
    });      
 
    // put the html in the output cell
    $("#output_html").val( output_html );
});
textarea {
  width: 100%;
  height: 8em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A<input id="a" value="a" /><br/ >
B<input id="b" value="b" /><br/ >
C<input id="c" value="c" /><br/ >
<textarea id="input_html">
  <a href="http://example.com">Link</a>
  <a href="http://example.com?foo=bar">Link</a>
  <p>Other elements get ignored</p>
  As does plain text
  <a href="">Blank Href</a>
  <a class="foo">No Href</a>  
</textarea>
<textarea id="output_html"></textarea>
<button id="apply">Apply</button>