2013-12-17 30 views
1

我想做一個單一的函數,可以處理===,!==排序元素。我不知道該怎麼辦this.Please建議我怎麼能做到這一點使單個函數來處理==,!==在jquery

HTML

<div class="aa">1</div> 
    <div class="aa">2</div> 
    <div class="aa">3</div> 
    <div class="aa">4</div> 
    <div class="aa">2</div> 
    <div class="aa">6</div> 

$ VAL = 2;

function getVal(div,symbol){ 
    div.filter(function() { 
       return parseInt($(this).html(), 10)===$val; //i want to use passed symbol in place of ===  
      }).show(); 
} 

getVal($('.aa'),'===') 

演示http://jsbin.com/EzEREFU/2/

+0

可能是使用:http://stackoverflow.com/questions/5834318/are-variable-operators-possible –

回答

3

需要應用一些聰明;)

function getVal(div,invert) { 
    div.filter(function() { 
     return (parseInt($(this).html(),10) === $val)^invert; 
    }).show(); 
} 

^是XOR運算。這應該是按位,但它適用於布爾人就好了。

要使用:

getVal($(".aa"),false); // "===" 
getVal($(".aa"),true); // "!==" 

如果你希望能夠在 「===」 或者,試試這個通過 「==!」:

function getVal(div,symbol) { 
    var invert = symbol.charAt(0) != "="; 
    div.filter(function() { 
     return (parseInt($(this).html(),10) === $val)^invert; 
    }).show(); 
} 

強制性Vanilla JS解決方案:

function getVal(className,symbol) { 
    [].forEach.call(document.getElementsByClassName(className),function(elm) { 
     if((parseInt(elm.firstChild.nodeValue,10) === $val)^invert) 
      elm.style.display = "block"; 
    }); 
} 
getVal("aa","==="); // show where equal 
getVal("aa","!=="); // show where not equal 

那是什麼?舊版瀏覽器? Psh,sod'em。如果人們通過禁用Windows Update故意讓我們的生活變得艱難,他們不配擁有我們的真棒網站。

1

除非您使用eval(..)(通常不推薦),否則實際上不能在javascript中傳遞字符串作爲運算符。我建議另一種選擇:

var equals = function(x,y) { return x === y; } 
var notEquals = function(x,y) { return x !== y; } 

現在,

function getVal(div,operation){ 
    div.filter(function() { 
       return operation(parseInt($(this).html(), 10),$val); 
      }).show(); 
} 

getVal($('.aa'),equals); //equals defined above. 

您可以創建這樣equalsnotEquals,等等。此外,你可以把它們放在一個字典,鍵進行自定義功能,您「符號」,並且該值是函數,並因此調用它。

1

你可以嘗試這樣的 -

$val=2; 


function getVal(div,symbol){ 
    div.filter(function() { 
    if(symbol=='equalsTo') 
     return parseInt($(this).html(), 10)===$val; 
    else if(symbol=='notEqualsTo') 
     return parseInt($(this).html(), 10)!==$val; 
    }).show(); 
} 

getVal($('.aa'), 'notEqualsTo'); //notEqualsTo or equalsTo 

例子 - http://jsbin.com/EzEREFU/4/

相關問題