我有两个JavaScript函数。一个通过其ID显示和隐藏div。到现在为止,这种情况一直很好。从那以后,我添加了一些我在网上找到的代码,这些代码阻止iOS在新窗口中打开链接(在全屏模式下)。由于每次我单击div以显示/隐藏该代码时都会添加此新代码,因此会触发该函数,但随后页面会刷新。有帮助吗?
我试图在所有可能的地方将return设置为false。 我将onclick更改为“ return function();”。 我将其更改为'function(); return false'。 我在两个函数中都放置了return false。
(function(document,navigator,standalone) {
//Code by Irae Carvalho http://about.me/irae
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if('href' in curnode ) {
e.preventDefault();
location.href = curnode.href;
}
return false;
},false);
}
})(document,window.navigator,'standalone');
function showHidden(id) {
var div = document.getElementById(id);
if (div.style.display == 'none') {
div.style.display = '';
}else{
div.style.display = 'none';
}
return false;
}
<!-- The code below is in my php file -->
<a onclick="showHidden('divID')">
单击链接可正确触发showHidden函数,但同时也刷新页面。我需要事件监听器来防止iOS处于全屏模式时在新窗口中打开链接,但我也不想在使用showHidden函数时触发点击监听器,或者至少不刷新页面。
答案 0 :(得分:0)
更改页面的原因是因为您没有阻止链接单击的默认操作,在这种情况下,该操作将加载其他页面。您可以通过在点击链接时调用e.preventDefault()
来实现此目的。
这里是一个例子:
(function(document,navigator,standalone) {
//Code by Irae Carvalho http://about.me/irae
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if('href' in curnode ) {
e.preventDefault();
location.href = curnode.href;
}
return false;
},false);
}
})(document,window.navigator,'standalone');
function showHidden(id) {
var div = document.getElementById(id);
if (div.style.display == 'none') {
div.style.display = '';
}else{
div.style.display = 'none';
}
return false;
}
var links = document.querySelectorAll('a');
links.forEach(function (el) {
el.addEventListener('click', function (e) {
e.preventDefault();
var divID = this.getAttribute('hide-id');
showHidden(divID)
})
})
<a hide-id="div1">Click here</a>
<div id="div1">
This is content
</div>
<br />
<br />
<a hide-id="div2">Click here</a>
<div id="div2">
This is content
</div>
答案 1 :(得分:0)
我发现的最佳解决方案是在eventlistener中添加一个检查,以检查href标记是否不为空:
if(curnode.href != '' )
只有在触发重定向后:
location.href = curnode.href;