在url中使用hashtag触发jquery单击元素

在url中使用hashtag触发jquery单击元素,jquery,Jquery,我想知道是否可以通过将用户发送到一个特定的url来触发弹出窗口,该url的末尾包含一个“#somerandomword” 所以通常他们点击页面上的一个按钮来触发弹出窗口,而我只希望当用户得到一个特定链接时触发弹出窗口 这可以在页面加载时轻松完成,只需在URL中查找哈希: $(document).ready(function(){ // the #-prefixed portion of the URL that serves // as a fragment identifie

我想知道是否可以通过将用户发送到一个特定的url来触发弹出窗口,该url的末尾包含一个“#somerandomword”


所以通常他们点击页面上的一个按钮来触发弹出窗口,而我只希望当用户得到一个特定链接时触发弹出窗口

这可以在页面加载时轻松完成,只需在URL中查找哈希:

$(document).ready(function(){

    // the #-prefixed portion of the URL that serves
    // as a fragment identifier for the document, from
    // www.example.com/page#fragment
    // document.location.hash would return #fragment
    let hash = document.location.hash;

    // because the hash identifies a fragment of
    // the document by its id, and the '#' character
    // specifies an id-selector in CSS we pass that
    // value to jQuery to select the correct element
    // and call the click() method - without arguments -
    // to trigger a click event:
    $(hash).click();
});
或者,
:target
的CSS选择器选择散列所针对的元素,因此也可以使用:

$(document).ready(function(){
    $(':target').click();
});
参考资料:

  • CSS:
  • JavaScript:
  • jQuery:

据我所知,这就是正在发生的事情。1.我们等到文件加载2。接下来,我们将url末尾的#存储在一个名为hash的变量中,这就是我有点困惑的地方。假设我的链接是www.google.com/puppies#dog,我们使用document.location.hash,并将其值“#dog”存储在变量“hash”中,因此hash现在包含“#dog”的值。似乎应该有某种IF语句,表示如果hash的值等于“#dog”,然后选择弹出按钮并触发一个单击事件。可能,但是,由于您在问题中从未提到,您只希望在答案中遗漏的特定片段/
id
s上触发事件。否则:是的,事情就是这样。