5

いくつかの変数があり、関数呼び出し間でそれらの値を保持したいのですが、javascript でこれを行う方法を誰でも共有できますか? グローバル変数を使用してみましたが、役に立ちません。たとえば、次のコードでは、呼び出されるたびに関数 jump 内でアラート値が常に同じであり、関数呼び出しごとに増加するわけではありません。アラート (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



}

ありがとうございます

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

これを行うには2つの方法があります。

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 に答える