【问题标题】:Div tag code extractordiv标签代码提取器
【发布时间】:2015-09-25 14:31:30
【问题描述】:

是否有可能有一个按钮,当点击它会提取特定 div 标签中的整个代码?可以在 javescript、jquery 或 php 中使用吗?

比如说:

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

例如,如果我单击网页上的“提取”按钮,则从 &lt;div class="extactMe"&gt;&lt;/div&gt; 的整个 div 标签将被复制到文本区域。请指教谢谢。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

您可以通过使用outerHTML 属性来实现此目的。试试这个:

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

Example fiddle

【讨论】:

    【解决方案2】:

    你试过了吗?

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

    【讨论】:

    • 请注意,这只会获取div 内的a 元素。
    • “$('.extractMe').prop('outerHTML');”成功了,但是您提供的解决方案是我将来可以使用的,所以也谢谢您:)
    【解决方案3】:

    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")

    【讨论】:

    • 太棒了,是的,我一定会关注这些主题,非常感谢你们,我真的很感激。感谢您提供完整的代码。立即添加书签 :) 案例已解决。
    猜你喜欢
    • 2018-02-20
    • 2018-03-23
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多