简体   繁体   English

如何将DOM元素的html分配给全局变量?

[英]how can i assign the html of a DOM element to my global variable?

I have a global variable "theClass" that I try to assign the contents of a DOM element after a click event has occurred, then I try to use it on another page, but it's not even being assigned in the first place! 我有一个全局变量“ theClass”,在单击事件发生后,我尝试为该元素分配DOM元素的内容,然后尝试在另一页上使用它,但它甚至没有被首先分配! This' the code, that returns ' false' in the console. 此代码,在控制台中返回“ false”。 I'm using jQuery. 我正在使用jQuery。

var theClass = '';
var getCategories = false;

$(document).ready(function(){

  $(document).on("click", ".nav li a", function() {
    theClass = $(this).html();
    getCategories = true;
  });

  console.log(theClass+" "+getCategories);
});

Going by your code, I am assuming by another page you actually mean another place in your code. 按照您的代码,我假设另一页实际上是您的代码中的另一个位置。 Your console log gets fired in the ready function, however, you are setting/updating the values in a function. 您的控制台日志会在ready函数中触发,但是,您正在设置/更新函数中的值。 Hence, your logging will not show result as expected. 因此,您的日志记录将不会显示预期的结果。

You can try logging in the event based function only. 您可以尝试仅登录基于事件的功能。 And will see that the first log gives default values and then subsequent clicks give updated values. 并且将看到第一个日志提供默认值,然后单击后续按钮提供更新值。

You can try something like following 您可以尝试以下操作

 $(document).on("click", ".nav li a", function() {
console.log(theClass+" "+getCategories);
theClass = $(this).html();
getCategories = true;

});

If you trying to set any value in global variable then it is valid in particular session,when I try to use it on another page then variable got initialize with global value as false. 如果您尝试在全局变量中设置任何值,则该值在特定会话中有效,当我尝试在另一页上使用它时,变量将使用全局值初始化为false。

Prefer below post for finding a another way. 希望在下面的帖子中找到另一种方法。

How can I pass values from one html page to another html page using javascript 如何使用javascript将值从一个html页面传递到另一html页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM