2013-05-18 34 views
-1

我在我的節目(在Dreamweaver運行)這條線是以下內容:如何爲特定的圖像源創建if語句?

function go() { 
if((document.test.test1.src == document.test.test2.src && document.test.test2.src == document.test.test3.src)) 

...... 
...... 
..... 
} 

此功能時,我有3個不同的圖像,其運行時或者在頁面三個彼此相等的。但是,我將如何讓它指定哪些圖像相互平等,而不是僅僅執行三者中的任何一個。

例如,如果一個圖像的標題爲'x',如果所有三個test1,test2,test的值都是'x',它將運行該函數並顯示此消息,但是,它會顯示其他圖像的相同消息(如果所有平等的'y')Id喜歡以某種方式分開的消息。

回答

0

我比較與當前圖像元素作爲參數分離,以一個單獨的函數,並使用該方法用不同的圖像對象:

function compare(imgElem){ 
    if((document.test.test1.src == document.test.test2.src && document.test.test2.src == document.test.test3.src)) 
    console.log(imgElem.id,"triggered"); 
    // or something else 
    } 
} 

compare(document.test.test1); 
compare(document.test.test2); 
compare(document.test.test3); 

然而溶液可能取決於您比較的元素數量不準確。對於大量元素,請嘗試使用地圖。

1

裏面你if聲明,你可以放置一個switch/case塊,以測試它的哪個圖像「X」,「Y」等,這不要緊,你檢查哪個圖像的src,因爲你已經檢查他們都是平等的。

if((document.test.test1.src == document.test.test2.src && document.test.test2.src == document.test.test3.src)) 
    switch (document.test.test1.src) { 
     case "x": 
      // Do stuff 
      break; 
     case "y": 
      // Do other stuff 
      break; 
    } 
1

如果我的理解正確,在您的代碼中您可以添加一個開關,例如

switch (document.test.test1.src) { 
     case 'y': 
     ........ 
     break; 
     case 'x' 
     ........ 
     break; 
} 

「........」指定要運行什麼,如果對象分別等於y或x。

0

這應該是相當簡單的實現

var a=document.test.test1.src; 
var b=document.test.test2.src; 
var c=document.test.test3.src 

var fn: { 
    x: function() { alert(messageX); }, 
    y: function() { alert(messageY); }, 
    z: function() { alert(messageZ);} 
}; 

if(a==b && b==c) { 
    if(fn.hasOwnProperty(a)) { 
     fn[a](); //you can also use 'b' or 'c' since they're all equal 
    } 
}