2016-11-24 35 views
0

我對彈出窗口(客戶端請求)有以下代碼。它使用我認爲是危險的eval。有沒有辦法重寫下面的腳本,所以它不使用(評估)?EVAL危險如何替換它

/* exported popup_default , popup_help , popup_sitemap , popup_footerlinks */ 

var matchClass = ['popup_default', 'popup_sitemap', 'popup_footerlinks', 'popup_help']; 
var newwindow = '' 

var popup_default = 'width=800,height=640,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=250,top=200'; 
var popup_help = 'width=700,height=650,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=100,top=100'; 
var popup_sitemap = 'width=1000,height=600,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=100,top=100'; 
var popup_footerlinks = 'width=800,height=500,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=250,top=200'; 

function pop_ups() { 
    "use strict"; 
    var x = 0; 
    var popClass; 
    while (x < matchClass.length) { 
    popClass = "'." + matchClass[x] + "'"; 
    $(eval(popClass)).click(function() { 
     var popurl = $(this).attr('href'); 
     var popupSpecs = $(this).attr('class'); 
     var popupName = Math.floor(Math.random() * 10000001); 
     newwindow = window.open(popurl, popupName, eval(popupSpecs)); 
     return false; 
    }); 
    x++; 
    } 
} 

$(function() { 
    "use strict"; 
    pop_ups(); 
}); 
+0

調用'eval'之前'popupSpecs'中的內容。 –

+0

不應該有一個簡單的'$('。'+ matchClass [x])'嗎?爲什麼你首先使用'eval'? – Bergi

+0

使用'eval'不是必需的,但它並不危險。 – nnnnnn

回答

4

你要使用

"use strict"; 
function makePopup(className, specs) { 
    $('.'+className).click(function(e) { 
     e.preventDefault(); 
     var popupName = Math.floor(Math.random()*10000001); 
     window.open(this.href, popupName, specs); 
    }); 
} 
var popups = { 
    popup_default:  'width=800,height=640,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=250,top=200', 
    popup_help:  'width=700,height=650,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=100,top=100', 
    popup_sitemap: 'width=1000,height=600,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=100,top=100', 
    popup_footerlinks: 'width=800,height=500,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=250,top=200' 
}; 
$(function() { 
    for (var key in popups) 
     makePopup(key, popups[key]); 
}); 

代替第一eval的,只是使用字符串連接。而不是第二個eval,使用一個對象查找屬性名稱。

0

感謝@Bergi

我更新腳本的最後一部分,因爲它扔了一個錯誤:

$(function() { 
    "use strict"; 
    for (var key in popups) { 
     if(popups.hasOwnProperty(key)) 
     { 
      makePopup(key, popups[key]); 
     } 
    } 
}); 
再次

感謝「的在體內應該if語句被包裹在一個」幫助