2016-11-03 25 views
1

我試圖得到一點jQuery的工作。它需要從textarea中選擇一些html代碼,在其中每 href添加一個後綴,然後在另一個textarea中顯示生成的html代碼。我不希望它呈現HTML,只顯示代碼。jQuery - 加載textarea,爲每個href添加後綴並顯示結果

此處,我一定要......

$('#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); 
}); 

它應該是足夠簡單,我覺得我很接近,但我已經有了一個完整的精神空白,爲什麼它不工作。任何人都在意找到我出錯的地方?

UPDATE 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> 

第一個鏈接不會有查詢字符串,第二個會?

+0

你能給你的輸入HTML代碼的例子嗎? –

回答

1

您的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); 
 
\t 
 
    // create a new var to store our new output 
 
    \t 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(); 
 
    });  
 
\t 
 
    // 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>