javascript - 为什么这个 if 语句不起作用?

标签 javascript html

<分区>

我正在测试一行代码,它检查变量是否为空。如果它为空,则会弹出提示。但是即使变量有东西,还是会弹出提示。

function myFunction(){
 
 if (site == null || variable == undefined) { 
  var site = prompt("Please enter a valid url:", "http://");
  document.cookie = 'Your bookmark is: '+ site;
  alert(unescape(document.cookie));
	document.getElementById("p1").innerHTML = '<a class="txt2" href="' + site + '" target="myframe">'   + site + '</a>';
 }
 
 else { 
  alert('yey its working');
 }
}
<a class="txt2" id="p1" onclick="myFunction()">Button</a>

代码在设置变量之后起作用,在加载页面之前再次弹出提示。

最佳答案

这是因为 变量 未定义(我们没有在任何地方设置它),if block 总是运行。

此外,如果 site 变量似乎在 myFunction 的范围内定义 -

Variables declared within a JavaScript function, become LOCAL to the function

理想的方法是检查 document.cookie 而不是变量 -

    function myFunction(){

 if (  document.cookie == '') { 
  var site = prompt("Please enter a valid url:", "http://");
  document.cookie = 'Your bookmark is: '+ site;
  alert(unescape(document.cookie));
    document.getElementById("p1").innerHTML = '<a class="txt2" href="' + site + '" target="myframe">'   + site + '</a>';
 }

 else { 
  alert('yey its working');
 }
}

myFunction();

检查它在 JSFiddle 中的工作情况

关于javascript - 为什么这个 if 语句不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46859681/

相关文章:

javascript - 如何处理 append() 函数之间发生的延迟?

jquery - 仅在一个 div 顶部的粘性部分

javascript - 使用 angularjs 中的自定义服务交换 ng-src 属性

javascript - 如何将 JSON 响应放入 jquery 中?

javascript - AngularJS - 分页不呈现在 $scope.Watch 变化(包括 CodePen)

html - CSS - 在前一个 li 下居中 li

javascript - Css 移动导航 body 滚动

html - css 和 z-index - 使我的提交按钮出现在我的搜索框内和前面

javascript - Jquery确认表单提交

通过 XHR 的 Javascript 请求