如何使用JavaScript从href中查找特定链接?
这是我第一次使用JS,所以请原谅我的问题。 我正在尝试为phpBB论坛创建一个用户脚本,它允许我自动为我创建的每个主题添加书签 我的方法是将onclick侦听器添加到submit按钮。 我将使用另一个问题中的代码:如何使用JavaScript从href中查找特定链接?,javascript,html,Javascript,Html,这是我第一次使用JS,所以请原谅我的问题。 我正在尝试为phpBB论坛创建一个用户脚本,它允许我自动为我创建的每个主题添加书签 我的方法是将onclick侦听器添加到submit按钮。 我将使用另一个问题中的代码: var submit = document.getElementsByTagName('input')[0]; submit.onclick = function() { ; } 在此之前,我想在页面上的一个HREF中找到一个链接,将该主题添
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
;
}
在此之前,我想在页面上的一个HREF中找到一个链接,将该主题添加到书签中,并将其存储为变量
我知道它将永远以
<a href="./viewtopic.php?f=FORUM_NUMBER&t=TOPIC_NUMBER&bookmark=1&hash=HASH"
我的问题是我不知道如何找到我需要的href并从中获取链接。没有发现任何类似的问题
提前感谢您的帮助您可以尝试
文档。getElementsByTagName(“a”)
;它返回加载到dom中的所有
的集合。
然后您可以在列表中找到它,并使用.href获取它的href属性。您可以尝试
document.getElementsByTagName(“a”)
;它返回加载到dom中的所有
的集合。
然后您可以在列表中找到它,并使用.href获取它的href属性。可能是这样的吗
var anchors = document.getElementsByTagName('a'); // get all <a> tags
var link = '';
if (anchors) {
// getAttribute(attributeName) gets the value of attributeName (in your case, the value of 'href' attribute
// .map(), .find() and .filter() are available methods for arrays in JS
// .startsWith() is an available method for matching strings in JS.
// You can even experiment with other regex-based string matching methods like .match()
// Use one of the following lines, based on what you require:
// to get the first matching href value
link = anchors.map(anchor => anchor.getAttribute('href')).find(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
// to get all matching href values as an array
link = anchors.map(anchor => anchor.getAttribute('href')).filter(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
}
var anchors=document.getElementsByTagName('a');//如果您是JS新手,请获取所有信息:)
快乐编码 也许是这样的
var anchors = document.getElementsByTagName('a'); // get all <a> tags
var link = '';
if (anchors) {
// getAttribute(attributeName) gets the value of attributeName (in your case, the value of 'href' attribute
// .map(), .find() and .filter() are available methods for arrays in JS
// .startsWith() is an available method for matching strings in JS.
// You can even experiment with other regex-based string matching methods like .match()
// Use one of the following lines, based on what you require:
// to get the first matching href value
link = anchors.map(anchor => anchor.getAttribute('href')).find(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
// to get all matching href values as an array
link = anchors.map(anchor => anchor.getAttribute('href')).filter(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
}
var anchors=document.getElementsByTagName('a');//如果您是JS新手,请获取所有信息:)
快乐编码 给链接一个类用途给链接一个类用途