【问题标题】:How to get content of div in to a variable?如何将 div 的内容放入变量中?
【发布时间】:2014-03-14 05:56:04
【问题描述】:

在我的 HTML 页面 div 标签中,id 为 div1,按钮 id=btn1 当我点击 Button 时,div 的内容应该会出现警告框

如何在html页面上打印?

【问题讨论】:

  • 你试过的。显示你的代码
  • Div 的内容也可能包含 DOM 元素。然后在这种情况下,您将以无格式字符串形式获取它们

标签: javascript jquery html


【解决方案1】:

你可以像这样使用contents

$('#btn1').on('click',function(){
   alert($('#div1').contents());
});

【讨论】:

    【解决方案2】:

    HTML

    <div id="div1">blah blah</div>
    <input type="button" id="btn1" onClick="alertbox();">
    <div id="new1"></div>
    

    JAVASCRIPT

    function alertbox(){
     var newText=document.getElementById("div1").innerHTML;
     alert(newText);//alert
     document.getElementById("new1").innerHTML=newText;//prints in new div
    }
    

    【讨论】:

      【解决方案3】:
      add "good morning" in div tag and a button with id button.
      
      your javascript code
      $(document).ready(function(){
        $("#button").click(function(){
       var data = $('div').text();
        alert (data);
      
        });
      });
      </script>
      

      【讨论】:

        【解决方案4】:
        $('.yourButtonClass').click(function() {
             var contentsOfDiv = $('.yourDivClass').contents();
             alert(contentsOfDiv);
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-20
          • 1970-01-01
          • 2018-10-08
          • 2014-06-06
          相关资源
          最近更新 更多