Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查一下有没有效果_Javascript_Testing_Cross Browser - Fatal编程技术网

Javascript 检查一下有没有效果

Javascript 检查一下有没有效果,javascript,testing,cross-browser,Javascript,Testing,Cross Browser,我试图测试特定浏览器上的可用内容(JavaScript方面) 例如,如果我只是键入以下内容: function checksetAttribute(){ if(document.getElementById("blar").setAttribute("name","blarDiv")){ alert("Your browser supports it."); } else{ alert("Your browser does not supp

我试图测试特定浏览器上的可用内容(JavaScript方面)

例如,如果我只是键入以下内容:

function checksetAttribute(){
    if(document.getElementById("blar").setAttribute("name","blarDiv")){
        alert("Your browser supports it.");
    }
    else{
        alert("Your browser does not support it.");
    }
}

这会返回属性是否工作的正确答案吗?

如果要测试某个属性是否工作,而不是
setAttribute
是否工作,那么这是错误的方法,因为
setAttribute
总是返回
未定义的
(==false)。相反,测试元素是否将属性名作为键,并使用一个新元素,而不是从DOM中提取的元素,因为DOM中的元素可能已被修改

function attributeWorks(attr, within) {
    return document.createElement(within || 'div').hasOwnProperty(attr);
}
我在
参数中添加了
,因为某些属性只存在于某些类型的元素上:例如,如果您总是针对
进行测试,那么函数将返回
false
,用于
href


如果要测试
setAttribute
函数是否工作,这仍然是错误的方法,因为如果未实现
setAttribute
,尝试执行它将抛出错误,而不是返回false。我们可以使用与上述相同的方法,简化为我们已经知道参数:

function setAttributeWorks() {
    return document.createElement('div').hasOwnProperty('setAttribute');
}

我猜想,如果不支持“setAttribute”,您那里的代码将失败

var a = document.createElement("div");
if(a.setAttribute){
    alert("VERY SUPPORTED");
}else{
    alert("Not supported");
}

这将检查setAttribute方法是否在dom元素上可用。

否。假设浏览器支持
document.getElementById
setAttribute
,它将只设置name属性。由于该方法(它是falsy),它将始终警告
“您的浏览器不支持它。”
——除非引发异常


它也不会检查浏览器是否支持
name
属性。

取决于您要测试的内容。如果要测试方法
setAttribute
是否存在,则不存在,如果不存在,则会抛出错误。
Object.prototype.setAttribute=1。我保证我不会这么做,但我不能在互联网上说。