javaScript变量中的更改是临时的,如何使其永久化.已附加控制台日志

Changein javaScript variable is temporary, how to i make it permanent. Console log is attached

本文关键字:日志 控制台 何使其 变量 javaScript      更新时间:2023-09-26

我对p标记进行了更改,只有一个p发生了更改。后来,我再次尝试显示更改,但没有看到更改。

我在做什么:

$(document).ready(function(){
  var html = "<div> <p></p> <p></p> <p></p> </div>";
  //making some changes to <p> tag
  $(html).find('p').each(function (){
    $(this).text("SomeText");
    console.log($(this).text());
  });
  // now again display the changes
  $(html).find('p').each(function (){
    console.log($(this).text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>(Look in the console for the result.)</div>

之所以会发生这种情况,是因为您每次都从html创建jquery对象。如果需要保留进度,则需要保存修改后的对象。

试试看:

  $(document).ready(function(){
   var html = "<div> <p></p> <p></p> <p></p> </div>";
           //making some changes to <p> tag
           var jHtml = $(html);
           jHtml.find('p').each(function (){
            $(this).text("SomeText");
                console.log($(this).text());
          });
          // now again display the changes
           jHtml.find('p').each(function (){
             console.log($(this).text());
         });
});

Jsfddle

您需要将更改后的HTML保存到某个位置。例如在DOM中或在变量中:

//making some changes to <p> tag
var newHTML = $(html).find('p').each(function (){

然后

// now again display the changes
$(newHTML).find('p').each(function (){

或者只创建jQuery HTML对象:

var html = $("<div> <p></p> <p></p> <p></p> </div>");

并将其用于您的方法:

html.find('p').each(
// etc

$(document).ready(function(){
  var html = $("<div> <p></p> <p></p> <p></p> </div>");
  //making some changes to <p> tag
  html.find('p').each(function (){
    $(this).text("SomeText");
    console.log($(this).text());
  });
  // now again display the changes
  html.find('p').each(function (){
    console.log($(this).text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>(Look in the console for the result.)</div>