2013-07-31 34 views
0

如何捕捉id標籤並寫入頁面。我想列出id名稱到textarea輸入中。我如何列出textarea的html名稱

謝謝。

HTML

<textarea id="textid" class="textclass"> 
    <div id="hello"><span id="world"></span></div> 
</textarea> 
    <p></p> 

JS

$("textarea").keyup(function() { 
     var value = $(this).val(); 
     $("p").text(value); 
}).keyup(); 

樣品 http://jsfiddle.net/6YRyP/2/

+0

所以,你想要什麼:textid或hello + world ??? –

+0

我想看「hello world」 – mrsarac

回答

2

如果你不想來解析從textarea的文本轉換爲HTML(如@roasted建議),你可以嘗試使用正則表達式:

$("textarea").keyup(function() { 
    var value = $(this).val(); 
    val = ''; 

    matches = value.match(/id="[^"]*/g); 

    for (i in matches) { 
     val += matches[i].substr(4) + ' '; 
    } 

    $("p").text(val); 
}).keyup(); 
+0

這是一個很好的解決方案! +1 –

+0

這兩種方法都有優點和缺點。一些缺點:當使用正則表達式時,你可以匹配任何包含'id =「的文本,並且在使用DOM對象時,你必須確保你有有效的HTML。 –

+0

最後完成:http:// css-tr。 com/htmltocss/ 謝謝@Michal – mrsarac

2

DEMO

$("textarea").keyup(function() { 
    var $content = $($('<div/>').html($.trim(this.value))), 
     ids = ""; 
    $content.find('[id]').each(function(){ 
     ids += " "+ this.id; 
    }); 

    $("p").text(ids.substring(0)); 
}).keyup(); 
+0

謝謝。這是完美的:) – mrsarac

0

這一個娃y以做到這一點:http://jsfiddle.net/6YRyP/7/

$("textarea").keyup(function() { 
    var value = $(this).val(); 
    $('body').append('<div id="search">'+value+'</div>'); 
    var listOfId = ""; 
    $('*', $('#search')).each(function() { 
     var currentId = $(this).attr('id'); 
     if (currentId != "") { 
      listOfId = listOfId + currentId + ' '; 
     } 
    }); 
    $('#search').remove(); 
    $("p").text(listOfId); 
}).keyup(); 
+0

它的作品。謝謝。 – mrsarac