[英]Javascript firing event on link
So I just need some help with this. 所以我只需要一些帮助。 I have an anchor on a separate HTML page, all these pages are linked with one external JS file.
我在一个单独的HTML页面上有一个锚点,所有这些页面都与一个外部JS文件链接。
So I have 所以我有
<!-- language: none -->
page1.html
page2.html
js.js
In page 1, I have a link that links to a specific anchor on page2, I want a javascript function to fire on page2 when a user opens that link. 在第1页中,我有一个链接到第2页上的特定锚点的链接,我想在用户打开该链接时在第2页上触发javascript函数。 I can't use onclick from the page1 link to grab the element on page 2 by ID and call the function in the js due to xss stopping it.
我无法使用page1链接中的onclick来获取第2页上的元素ID,并且由于xss停止而调用js中的函数。
So tl;dr 所以tl;博士
page1.html -> Link is here page1.html - >链接在这里
page2.html -> destination is here, when user arrives at destination, I want a function in the js file to fire. page2.html - >目的地在这里,当用户到达目的地时,我想要在js文件中触发一个函数。 But ONLY when he arrives at the specific anchor on page 2 via link.
但只有当他通过链接到达第2页的特定锚点时。 (ex: link on p1 goes to
page2.html#destination
) (例如:p1上的链接转到
page2.html#destination
)
Is this possible? 这可能吗? I've tried attaching
onfocus
, onevent
, and onchange
handlers to the anchor on page two but it's not working. 我已尝试将
onfocus
, onevent
和onchange
处理程序附加到第2页的锚点,但它不起作用。
Yes; 是; use the property
window.location.hash
. 使用属性
window.location.hash
。 Like so (on page2.html): 像这样(在page2.html上):
if(window.location.hash === '#destination') {
// Call your function here
}
If you want some JS in page2 to run only when page2 is arrived at a specific way, then the usual way to do that is to have page1 add a query parameter when going to page2 and have page2 look for that query parameter. 如果你想让page2中的某些JS仅在以特定方式到达page2时运行,那么通常的方法是在转到page2时让page1添加查询参数并让page2查找该查询参数。 When page2 starts up, it looks for the query parameter and runs some extra JS if it's present.
当page2启动时,它会查找查询参数并运行一些额外的JS(如果它存在)。
So, if page1 is page1.html
and page2 is page2.html
, then your special link in page1 will link to page2.html?action=1
. 因此,如果page1是
page1.html
而page2是page2.html
,那么page1中的特殊链接将链接到page2.html?action=1
。
The javascript in page2.html will look for action=1
in the URl and run it's special JS only if it's on page2.html and it finds action=1
in the URL. page2.html中的javascript将在URl中查找
action=1
,并且仅当它在page2.html上并且在URL中找到action=1
时才运行它的特殊JS。
All query parameters are available via window.location.search
. 所有查询参数都可以通过
window.location.search
。 If you aren't expecting any other query parameters, then you can just use: 如果您不期望任何其他查询参数,那么您可以使用:
if (window.location.search == "?action=1") {
// execute your code here
}
If there could be other query parameters, then you can use this: 如果可能有其他查询参数,那么您可以使用:
if (window.location.search.match(/(\?|&)action=1($|&)/)) {
// execute your code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.