【问题标题】:How can I get the innerHTML of a text that is overwritten with javascript如何获取被 javascript 覆盖的文本的 innerHTML
【发布时间】:2019-05-26 16:37:01
【问题描述】:

HTML:

<div class="col answer">
    some text
</div>

js:

$(".answer").text("Here we change the text" );
$(".answer").click(function(E) {
    console.log(E).html();
  });

控制台输出:未定义

【问题讨论】:

  • console.log 返回undefined...你的意思是console.log($(this).html())吗? E指索引
  • console.log($(E.target).html()) 将记录 html。或console.log(E.target.innerHTML)

标签: javascript jquery html click innerhtml


【解决方案1】:

您需要使用$(this).html() 而不是(E).html()。您的代码应如下所示:

console.log($(this).html());

演示:

$(".answer").text("Here we change the text");
$(".answer").click(function() {
  console.log($(this).html());
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="col answer">
  some text
</div>

【讨论】:

    【解决方案2】:

    因为这也是在 Javascript 中发布的,所以这里有一个普通的选项来做同样的事情:

    <div class="col answer">
        some text
    </div>
    
    <script>
    
        var x = document.getElementsByClassName("answer");
        var y;
        for (y = 0; y < x.length; y++) {
          x[y].innerHTML = "Here we change the text";
        } 
    
        window.onload = function() {
            document.addEventListener('click', function (event) {
            	var target = event.target;
            	if(target.matches('.answer')){
              	console.log(target.innerHTML);
              }
            }, false);
        }
    </script>

    【讨论】:

      【解决方案3】:

      您需要innerHTML 还是text??如果您需要文字,请使用.text() 方法。

      $(".answer").text("Here we change the text" );
      $(".answer").off().on('click',function() {
          console.log($(this).html());
      });
      

      【讨论】:

        猜你喜欢
        • 2021-09-27
        • 1970-01-01
        • 2016-01-05
        • 1970-01-01
        • 1970-01-01
        • 2011-06-02
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多