如何用jQuery获取一个可信的div的内容?

时间:2017-03-27 14:04:08

标签: javascript jquery html

<!doctype html>
<html>
    <head>
        <title>My test</title>
        <link rel="stylesheet"  type="text/css" href="editor/style.css">           
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>           
    </head>
   <body>
        <div contenteditable="true" class="doc">
            <p contenteditable="true" class="letters" >My editor</p>
        </div>
        <button id="but">Done Editing</button> 

        <script>
            $(document).ready(function() 
            {
                $('#but').on('click',function(){
                    //want to obtain all the text within the contenteditable div on clicking the button
                });
            });
        </script>
    </body>
</html>

点击&#34;完成编辑&#34;按钮我想获得在我的contenteditable div中输入的所有文本。 显然,命令如

var content = $('.doc').text();

3 个答案:

答案 0 :(得分:1)

你的div没有id="my-contenteditable-div",这就是为什么它不起作用。

您可以使用jQuery以这种方式访问​​它:

$(document).ready(function() {
  $('#but').on('click', function() {
    console.log($('#myDiv').html());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="myDiv" contenteditable="true">DIV CONTENT</div>
<button id="but">Done Editing</button>

其他替代方案here

答案 1 :(得分:1)

您应该使用有效选择器。由于div有一个类,请使用类选择器$('.doc')

要了解有关选择器的更多信息,请参阅the api docs

<!doctype html>
<html>

<head>
  <title>My test</title>
  <link rel="stylesheet" type="text/css" href="editor/style.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>

<body style="overflow: hidden; margin-top: 50px">
  <div contenteditable="true" class="doc">
    <p contenteditable="true" class="letters">My editor</p>
  </div>
  <button id="but">Done Editing</button>

  <script>
    $(document).ready(function() {
      $('#but').on('click', function() {
        console.log($('.doc').text());
      });
    });
  </script>
</body>

</html>

答案 2 :(得分:1)

使用适当的选择器.letters

$(document).ready(function() {
      $('#but').on('click', function() {
          var content = $('.letters').html();
            console.log(content);
            // do the process here
          });
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>

<head>
  <title>My test</title>
  <link rel="stylesheet" type="text/css" href="editor/style.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>

<body style="overflow: hidden; margin-top: 50px">
  <div contenteditable="true" class="doc">
    <p contenteditable="true" class="letters">My editor</p>
  </div>
  <button id="but">Done Editing</button>
</body>

</html>