如何获取被 javascript 覆盖的文本的 innerHTML

How can I get the innerHTML of a text that is overwritten with javascript

HTML:

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

js:

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

控制台输出:未定义

您需要使用 $(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>

因为这也在 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>

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

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