jQuery if url hash, click event/activate javascript
jQuery if url hash, click event/activate javascript
所以从主页上,我有一个指向产品列表页面的链接。产品页面具有展开/折叠div。
我需要适当的div 来扩展,具体取决于 url# 是什么。
所以主页上的链接是
<a href="/out-products.php#healthysnacks">healthy snacks</a>
当我单击上面的链接时,我正在尝试在产品页面上激活它:
<a href="javascript:ReverseDisplay('products4')" id="healthysnacks"> Healthy Snacks</a>
我已经尝试了其他一些代码,我发现这些代码通过检查哈希标签来触发点击,但它们都没有正常工作,我认为这是因为 ReverseDisplay js。请任何见解都会有所帮助。
谢谢
您可以在产品页面的文档就绪功能中进行以下更改:
简单修复:由于 jQuery id 选择器是#elementId
的,您可以简单地使用 window.location.hash
值作为 id 选择器,并使用它来定位所需的元素。
if ( window.location.hash ) {
$(window.location.hash).click(); //clicks on element specified by hash
}
更好:除了上述内容之外,从标记中删除 js。
$('#healthysnacks').click(function(e) {
e.preventDefault();
ReverseDisplay('products4');
});
然后,完成此操作后,使用上面的$(window.location.hash).click()
代码。此外,将您的链接更改为:
<a href="#" id="healthysnacks"> Healthy Snacks</a>
您可以使用 Location
对象的 hash
属性,请尝试以下操作:
$(document).ready(function(){
var id = window.location.hash;
$(id).trigger('click')
})
由于您使用的是 jQuery 而不是javascript:
协议,因此您可以使用 jQuery click
方法:
$('#healthysnacks').click(function() {
// do something here
})
这里建议的答案是有效的,但是...
在jQuery选择器中使用window.location.hash时要格外小心,因为这可能导致XSS漏洞。 $() 还可以创建一个 HTML 元素,并且使用精心构造的哈希值,有人可以执行任意 JavaScript 代码。
例如
http://my-website.com/about#'><img src=x onerror=alert(/XSSed/)>
如果 my-websites.com/about 页面在jQuery选择器中使用window.location.hash,则该错误代码最终将被执行。
- issue with FB.Event.subscribe
- Angularjs :$routeChangeStart event
- event.prventDefault()持续多久
- <text区域>在我的html中包含event.keycode==13之后,wrap就不起作用了
- KeyDown event for CKeditor
- Javascript events: window.event vs argument reference (funct
- 动态填充Bootstrap选择选择器:change event dos'不起作用
- <td> focusin event .addclass
- event.preventDefault阻止ajax调用
- google.maps.event.addDomListener(window, 'load', fun
- jQuery event.target is_a_child_of(element)
- event.stopPropagation()在firefox javascript中不起作用
- asp.net text onkeyup event
- 如何从ondragend获取正确的event.pageX
- 面料:“;鼠标:向下”;在event.target中未返回对象
- 使用event.target.classlist区分按钮颜色
- event.keycode vs event.which
- 将字符串作为参数传递给函数onclick event jquery
- iFrame onload JavaScript event
- jQuery if url hash, click event/activate javascript