使用JavaScript获取锚链接文本

3

我不知道是否可能!也许我的想法也是错误的。我想调用一个与我Wordpress博客中所有链接对应的搜索。

我在这个网站上使用Ajax调用进行其他搜索。如何从HTML中的超文本标记中检索链接文本。 例如:<a href='www.example.com'>demo</a>。在这里,我希望获得“demo”作为输入。

谢谢。

2个回答

4

试试这个:

var links_html_list = [];

var links = document.getElementsByTagName('a');

for(var l in links) {
   if(typeof links[i] == undefined) continue;
   links_html_list.push(links[i].innerHTML);
}

function search(term) {
   var results = [];
   for(var l in links_html_list) {
       var cur = links_html_list[l];
       if(typeof cur == undefined) continue; 
       if(cur.indexOf(term) != -1) results.push(cur);
   }
   return (results.length > 0) ? results : null;
}

search函数的作用是循环遍历字符串列表,如果其中有包含term(使用indexOf方法)的字符串,则将其推送到一个数组中并返回。如果没有匹配项,则返回null


1
你可以使用


$homePageText = file_get_contents(file.html);
preg_match_all('/<a .*?>(.*?)<\/a>/',$homePageText,$matches);

然后所有锚文本元素将被存储在数组$matches中。


谢谢您的回复。但是,这种方法对我没有帮助...我遇到了一个错误,提示“未知修饰符'a'”。 - Aadi
抱歉,请在“/a”之前添加反斜杠。我已经编辑了我的发布的代码。 - Josiah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接