我需要在JavaScript中创建一个函数,以便在给定的url中找到href
,并将其作为字符串返回。
例如:http://stackoverflow.com/
因此该函数以:function example(url) {}
开头
我想在此网址中找到包含单词google
的第一个链接。
在此页面中,有一个类似<a href:"http://google.com/asdasdadsa/asdada">
的链接
该函数将整个链接作为字符串返回。
答案 0 :(得分:3)
所以基本上我可以收集的内容,你想查看页面上的每个链接,如果它包含一些字符串(即谷歌),则获取整个URL。
这是一个找到与某个字符串匹配的第一个链接的函数:
function checkLinks( searchString ) {
var url;
// Go through each link
$('a').each( function ( ) {
// Check if the search string exists
if( $(this).attr('href').indexOf(searchString) != -1 ) {
url = $(this).attr('href');
// If we've found one, stop the each.
return false;
}
});
return url;
}
我把一个jsfiddle放在一起,展示了如何使用这个功能的例子:
编辑:
我刚刚看到你需要在远程网址上执行此操作。您可能需要使用AJAX加载代码,然后在您拥有的代码上运行它。不幸的是由于same origin policy,您无法直接获取此信息,因此您需要在服务器上运行服务器端脚本(例如使用PHP)来加载外部页面的内容,然后来自你的JS的AJAX调用将它拉入你的javascript。
修改后的版本包含一些代码的AJAX加载,然后查找该代码:
// Create a function to do the actual search
function checkLinks( code, searchString ) {
var url;
// Search the code for all <a> tags, the loop over them
$(code).find('a').each( function ( ) {
// Check if there is a match (indexOf returns -1 if not)
if( $(this).attr('href').indexOf(searchString) != -1 ) {
// set the "url" variable to the href
url = $(this).attr('href');
// Stop looping
return false;
}
});
return url;
}
// Now, when the page loads, attach an AJAX call to a button with ID "linkchecker"
$( function ( ) {
$('#linkchecker').click( function( ) {
var code;
// Perform the AJAX call, load the data and call our function above to find "google.com"
$.get( 'load_code.php?url=http://www.google.com', function( data ) {
code = data;
alert( checkLinks( code, 'google.com' ) );
});
});
});
load_code.php
可能看起来像这样(可能有一些错误检查等):
<?php
$htm = file_get_contents($_GET['url']);
echo $htm;
?>
更新:使用原始Javascript
我们将从上方修改checkLinks
以使用原始Javascript:
function checkLinks( code, searchString )
{
var url;
// We need to create an HTML document element so we can use javascript dom functions on it.
var doc = document.createElement("html");
doc.innerHTML = code; // put the code into the document
// Get all links in the code
var links = doc.getElementsByTagName("a")
// Loop over all links
for (var i=0; i<links.length; i++) {
// Check if the search string (e.g "google.com") is found in the href of the link
if( links[i].getAttribute("href").indexOf(searchString) != -1 ) {
// Set it to the return value
url = links[i].getAttribute("href");
// stop looping
break;
}
}
return url;
}
首先,您需要设置Ajax请求对象。问题是这在浏览器之间有所不同,因此您需要一个令人不快的代码来跨它们生成它。以下是tiztag ajax tutorial:
修改的内容function makeAJAXObject(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
return ajaxRequest;
}
好的,现在我们已经获得了AJAX对象,我们想让它加载一个页面,然后告诉它如何处理我们得到的东西:
/*
* A function to load a given URL and process the code from it.
* It takes three arguments:
* php_handler The name of the PHP file that will load the code (or ASP, or whatever you choose to use)
* url The URL to be loaded.
* searchString The string to find in the links (e.g. "google.com").
*/
function load_page( php_handler, url, searchString )
{
// Get the ajax object using our function above.
window.ajax = makeAJAXObject( );
// Tell the AJAX object what to do when it's loaded the page
window.ajax.onreadystatechange = function(){
if(window.ajax.readyState == 4){ // 4 means it's loaded ok.
// For simplicity, I'll just alert this, but you would put your code to handle what to do when a match is found here.
alert(checkLinks( window.ajax.responseText, searchString ));
}
}
// Set up the variables you want to sent to your PHP page (namely, the URL of the page to load)
var queryString = "?url=" + url;
// Load the PHP script that opens the page
window.ajax.open("GET", php_handler + queryString, true);
window.ajax.send(null);
}
最后一件事是在页面加载时将其附加到按钮:
window.onload = function( ) {
document.getElementById('linkchecker').onclick = function( ) {
load_page('load_page.php', 'http://www.example.com', 'google');
}
}
请注意,可能内置WinJS功能来处理一些AJAX内容,但我从未尝试过Win 8应用程序开发,因此我不了解它们! / p>