【问题标题】:Select all links and forms without jQuery选择所有没有 jQuery 的链接和表单
【发布时间】:2013-01-28 02:56:28
【问题描述】:

如何在不包含 jQuery 的情况下选择所有 aform 标签?

我最终会尝试做以下事情:

$("a").click(function {
    window.onbeforeunload = null;
});

$("form").submit(function {
    window.onbeforeunload = null;
});

但如果有更紧凑的方法可以做到这一点,我真的宁愿不包含 jQuery(甚至 Sizzle.js)。

【问题讨论】:

标签: javascript jquery selector sizzle


【解决方案1】:

你可以像这样使用document.querySelectorAll()

var els = document.querySelectorAll( 'a' );
for( var i=els.length; i--; ) {
  els[i].addEventListener( 'click', function(){ window.onbeforeunload = null; } );
}

<form> 标签与此类似。

它在大多数现代浏览器中都可用 (caniuse.com)。

【讨论】:

  • 我得到了'undefined' is not a function for var els = document.querySelectorAll( 'a' );...尽管如果我直接在 Web Inspector 中运行它,它就可以工作。我需要做一些onload 的事情,或者类似的事情?
  • @Shpigford 不需要任何设置。您在哪个浏览器中进行测试?
  • @Shpigford 无法仔细检查那个,抱歉。但是,语法是正确的。
【解决方案2】:

应该这样做:

var links = document.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    links[i].addEventListener("click", function() { console.log("Clicked"); window.onbeforeunload = null; });
}

要获取表单提交,您可以执行以下操作:

<script>
    do_function() { window.onbeforeunload = null; }
</script>
<form action="" onsubmit="do_function()" method="">

编辑: 将两者结合起来:

var links = document.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    links[i].addEventListener("click", function() { console.log("Clicked"); window.onbeforeunload = null; });
}
var forms = document.getElementsByTagName("form");
for (var i = 0; i < forms.length; i++) { 
    forms[i].addEventListener("submit", function() { console.log("Submitted"); window.onbeforeunload = null; });
}

Fiddle

【讨论】:

猜你喜欢
  • 2017-07-29
  • 2017-08-29
  • 2012-03-11
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多