5

我有一些变量,我想在函数调用之间保留它们的值,任何人都可以分享如何在 javascript 中执行此操作。我曾尝试使用全局变量,但这无济于事。非常感谢帮助,例如在下面的代码中,每当调用内部函数跳转时,警报值总是相同的,它不会为每个函数调用增加。警报(this.prevVal);和警报(this.currentVal);

// We're using a global variable to store the number of occurrences
var MyApp_SearchResultCount = 0;
var currSelected = 0;
var countStr = 0; 




//var prevEl,el;

// helper function, recursively searches in elements and their child nodes
function MyApp_HighlightAllOccurencesOfStringForElement(element,keyword) {
  if (element) {
    if (element.nodeType == 3) {        // Text node
      while (true) {
        var value = element.nodeValue;  // Search for keyword in text node
        var idx = value.toLowerCase().indexOf(keyword);

        if (idx < 0) break;             // not found, abort

        var span = document.createElement("span");
        var text = document.createTextNode(value.substr(idx,keyword.length));
        span.appendChild(text);
        span.setAttribute("class","MyAppHighlight");
        span.style.backgroundColor="yellow";
        span.style.color="black";
        text = document.createTextNode(value.substr(idx+keyword.length));
        element.deleteData(idx, value.length - idx);
        var next = element.nextSibling;
        element.parentNode.insertBefore(span, next);
        element.parentNode.insertBefore(text, next);
        element = text;
        window.MyApp_SearchResultCount++;   // update the counter
        //countStr = MyApp_SearchResultCount;   

      }
    } else if (element.nodeType == 1) { // Element node
      if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
        for (var i=element.childNodes.length-1; i>=0; i--) {
          MyApp_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
        }
      }
    }
  }
}

// the main entry point to start the search
function MyApp_HighlightAllOccurencesOfString(keyword) {

    alert("test");

  //MyApp_RemoveAllHighlights();
  MyApp_HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());
    alert(window.MyApp_SearchResultCount);  
}

// helper function, recursively removes the highlights in elements and their childs
function MyApp_RemoveAllHighlightsForElement(element) {
  if (element) {
    if (element.nodeType == 1) {
      if (element.getAttribute("class") == "MyAppHighlight") {
        var text = element.removeChild(element.firstChild);
        element.parentNode.insertBefore(text,element);
        element.parentNode.removeChild(element);
        return true;
      } else {
        var normalize = false;
        for (var i=element.childNodes.length-1; i>=0; i--) {
          if (MyApp_RemoveAllHighlightsForElement(element.childNodes[i])) {
            normalize = true;
          }
        }
        if (normalize) {
          element.normalize();
        }
      }
    }
  }
  return false;
}

// the main entry point to remove the highlights
function MyApp_RemoveAllHighlights() {
  window.MyApp_SearchResultCount = 0;
  MyApp_RemoveAllHighlightsForElement(document.body);
}


function goNext(){
    jump(1);
}
function goPrev(){
    jump(-1);
}

var prevSelected = 0;
var currSelectedGlo = 0; 

this.prevVal = 0; 
this.currentVal = 0;

function jump(howHigh){

    this.prevVal = this.currentVal; 
    this.currentVal = this.currentVal + 1; 

    alert(this.prevVal);
    alert(this.currentVal);


    prevSelected = currSelected;
    currSelected = currSelected + howHigh;
    //window.currSelectedGlo = currSelected + howHigh; 
    //currSelected = window.currSelectedGlo;

    //alert("prevSelected" +prevSelected);
    //alert("window.currSelected "+ currSelected);

    //alert(window.MyApp_SearchResultCount);
    //alert(currSelected);
    if (currSelected < 0){  
        currSelected = window.MyApp_SearchResultCount + currSelected;
    }
    if (currSelected >= window.MyApp_SearchResultCount){
        currSelected = currSelected - window.MyApp_SearchResultCount;
    }

    prevEl = document.getElementsByClassName("MyAppHighlight")[prevSelected];
    //alert(window.prevEl);
    if (prevEl){
        prevEl.style.backgroundColor="yellow";
    }
    el = document.getElementsByClassName("MyAppHighlight")[currSelected]; 
    el.style.backgroundColor="green";
    el.scrollIntoView(true); //thanks techfoobar



}

谢谢 djrecker

4

4 回答 4

5

您可以使用全局变量:

var value = 0;

function next() {
    return value++;
}

console.log(next());
console.log(next());

或者更好的是,一个具有属性和方法的对象:

function Counter() {
    this.value = 0;
}

Counter.prototype.next = function() {
    return this.value++;
};

var counter = new Counter();
console.log(counter.next());
console.log(counter.next());
于 2013-01-06T20:20:47.080 回答
1
this.prevVal = 0; 
this.currentVal = 0;

function jump(howHigh){    
    this.prevVal = this.currentVal; 
    this.currentVal = this.currentVal + 1; 

这不是创建全局变量的常用方法,如果用于此目的很容易出错。此外,在使用严格模式时,您可能会遇到额外的障碍。

为了使您的变量可靠地全局化,请执行

var prevVal = 0; 
var currentVal = 0;

function jump(howHigh){ 
    prevVal = currentVal; 
    currentVal = currentVal + 1; 

小提琴(我也改成+1+howHigh:http: //jsfiddle.net/4uGZ3/

你不能得到比这更多的全局,但如果你想让你的变量在页面导航、重新加载等中存活下来,你必须使用LocalStorage(在 IE7 中不起作用)或 cookie:

function jump(howHigh){ 
    var currentVal = +localStorage.getItem("currentVal"); // + to cast to number
    prevVal = currentVal; 
    currentVal = currentVal + 1; 
    localStorage.setItem("currentVal", currentVal); // store back

再次,小提琴:http: //jsfiddle.net/uKtcY/7/


这是通常的使用模式this

function X(){
    this.prevVal=0;
    this.currenVal=0;
}
X.prototype.jump = function(){
    this.prevVal = this.currentVal; 
    this.currentVal = this.currentVal + 1; 
...

//test:
var x1 = new X();
var x2 = new X();

x1.jump(1); // 0=>1
x2.jump(2); // 0=>2
x1.jump(3); // 1=>4

...
于 2013-01-06T20:34:00.133 回答
0

有两种方法可以做到这一点:

1)一个全局变量:

 someVar = 0;

 function increaseSomeVar(){

      someVar++;
 }

2)返回一个变量:

 var someVar = 0;

 function increaseSomeVar(somelocalVar){
    somelocalVar++;
    return(somelocalVar);   
 }

 someVar = increaseSomeVar(someVar);
于 2013-01-06T20:24:17.793 回答
-1

首先,使用全局变量通常是个坏主意。

由于 javascript 通过引用传递对象,因此您可以使用具有数字的对象作为您更新的属性。通常,您可以随意传递此对象,除非您调用的函数会使您失去当前范围,例如setTimeout. 在这种情况下,您可以使用 jquery 的 bind 函数来跟踪变量和范围,例如

 MyApp_HighlightAllOccurencesOfStringForElement.bind(this, element, keyword);
于 2013-01-06T20:26:39.940 回答