2

我需要在 JavaScript 中创建一个函数来定位href给定的 url,并将其作为字符串返回。

例如:http://stackoverflow.com/

所以函数开始于:function example(url) {}
我想在这个 url 中找到第一个包含单词的链接google

在此页面中,有一个链接,例如<a href:"http://google.com/asdasdadsa/asdada">
该功能是将整个链接作为字符串返回。

4

1 回答 1

3

所以基本上从我能收集到的信息来看,你想查看页面上的每个链接并获取整个 URL,如果它包含一些字符串(即 google)。

这是一个查找与某个字符串匹配的第一个链接的函数:

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,展示了如何使用此函数的示例:

http://jsfiddle.net/K9KvS/1/

编辑:

我刚刚看到您需要在远程 URL 上执行此操作。您可能需要使用 AJAX 加载代码,然后在您拥有的代码上运行它。不幸的是,由于相同的来源策略,你不能直接得到这个,所以你需要在你的服务器上运行一个服务器端脚本(例如使用 PHP)来加载外部页面的内容,然后从 AJAX 调用您的 JS 将其拉入您的 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 教程修改的:

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 应用程序开发,所以我不了解它们!

于 2013-05-30T03:37:25.043 回答