Итак, в основном из того, что я могу собрать, вы хотите посмотреть на каждую ссылку на странице и получить весь 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/
EDIT:
Я только что видел, что вам нужно сделать это на дистанционном URL. Вероятно, вам нужно использовать AJAX для загрузки кода, а затем запустить его на код, который у вас есть. К сожалению, из-за same origin policy вы не можете получить это напрямую, поэтому для загрузки содержимого внешней страницы вам потребуется запустить серверный скрипт на вашем сервере (например, с помощью 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;
?>
Update: Использование Raw Javascript
Мы изменим checkLinks
от выше для использования raw 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, поэтому я не знаю их!
Я смущен. Является ли URL таким? 'http://example.com?param1=abc¶m2=d&...http%3A//www.google.com" ' – Isaac
Я думаю, вы имеете в виду" вы хотите найти первый href из набора ссылок на странице который содержит слова «google»? – prograhammer
Нет, URL-адрес находится в исходном коде example.com, как ссылка где-то на веб-сайте. Спасибо за быстрый ответ. –