【发布时间】:2012-03-01 06:55:18
【问题描述】:
这适用于桌面 safari,但在 iOS 版本中不会弹出警报。是否可以绑定到 iOS 中的“html”元素?每当用户单击页面上的其他位置时,我想关闭一个下拉菜单。
$('html').bind("click", function(){alert("clicked!")})
编辑
由于 jsfiddle 嵌入在 iframe 中,因此将其发布为 html,这显然解决了我的问题。在桌面 safari 上打开此页面可以正常工作,但在 iOS 模拟器中单击时不会显示任何内容。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('html, body').bind("click", function(){alert("html or body")})
$(document).bind("click", function(){alert("document")})
});
</script>
<body>
</body>
</html>
编辑 2
这对我在 iOS 模拟器或我的 iPhone 上也不起作用。如果我将 delegate() 放在我的应用程序中并单击链接,我确实会收到警报。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<body>
</body>
<script type="text/javascript">
$(document).delegate('html, body', "click", function(){alert("html or body")});
</script>
</html>
编辑 3
这行得通!
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<body>
<div id="stuff">applesauce</div>
<div>other stuff</div>
</body>
<script type="text/javascript">
$(':not[#stuff]').on( "click", function(){alert("not stuff")});
</script>
</html>
【问题讨论】:
-
你试过用 $('body') 代替吗?
-
为什么要使用 $('body') 代替?有没有地方说要听身体的参考?
-
我没有任何参考资料,但每个设备处理 javascript 的方式略有不同,因此 iOS 使用 $('html') 的方式可能有所不同。
-
我刚刚查看了 jquery 代码code.jquery.com/jquery-1.7.1.js 并在初始化中发现了这个,if (selector === "body" && !context && document.body) {...}。 “html”没有类似的东西,所以我假设他们会将该部分留给设备,而不是像处理正文那样手动处理它。
-
如果这是一个 jQuery 问题,我会感到惊讶,并且您链接到的代码部分似乎只是对选择器的优化。
标签: javascript jquery html ios