Div标签代码提取器

Div tag code extractor

本文关键字:提取 代码 标签 Div      更新时间:2023-09-26

是否有可能有一个按钮,当点击它将提取特定div标签内的整个代码?它是可能在javascript, jquery,或php?

例如:

<div class="extactMe">
<a href="http://stackoverflow.com"><img src="icon.png"></a>
</div>

例如,如果我点击网页上的"Extract"按钮,从<div class="extactMe"></div>的整个div标签将被复制到一个文本区域。

您可以通过使用outerHTML属性来实现这一点。试试这个:

var divHtml = $('.extractMe').prop('outerHTML');
$('textarea').val(divHtml);

例子小提琴

你试过了吗?

var extracted = $('.extractMe').html();

完整的示例在JSFiddle: https://jsfiddle.net/jo37u3xs/

这里不涉及PHP

Javascript部分:

$(document).ready(function() {
    // when you click the button
    $("#button-extract").click( function() {
        // get the html of the div
        var divContent = $('div.extractMe').html();
        // insert the html of the div into the textarea
        $("textarea#my-textarea").val(divContent);        
    });
});
HTML:

<div class="extractMe">
   <a href="http://stackoverflow.com"><img src="icon.png">Yo, man. The image is missing.</a><br/>
</div>
<br/>    
<button type="button" id="button-extract">Extract</button>
<br/><br/>   
 <textarea cols="50" rows="10" id="my-textarea">
Its empty at the start. Err, not really.
</textarea>  

请查看以下jQuery函数来了解它们的作用:

  • .click ()
  • . html ()
  • .val ()
  • 和jQuery选择器:$ (" . class)和$ (" # id ")