[英]using jquery to create array of elements in a given class then selecting a random link within that class and opening it
var linksInCategory = document.id($('.CategoryTreeLabel').href);
var randomLinkArray = new Array(linksInCategory);
// CategoryTreeLabel是所有錨標簽都包含的類,該類包含帶有指向所需頁面鏈接的href
function goThere(link)
{
var the_url = function pickRandomURL () {
var random_url = randomLinkArray[Math.floor(Math.random()*randomLinkArray.length)];
the_url = random_url;
}
var good_url = fixURL(the_url);
var new_window = window.open(good_url,"new_window","menubar, resizeable. location, toolbar, status, scrollbars");
}
function fixURL(the_url) {
var the_first_seven = the_url.substring(0,7);
the_first_seven = the_first_seven.toLowerCase();
if (the_first_seven != 'http://')
{
the_url = "http://" + the_url;
}
return the_url;
}
</script>
</head>
<body>
<form name="the_form">
<input type="button" name="the_url" class="broadGroups" onClick="goThere(this)" src="the_url" value="Sports"></input>
<input type="button" name="the_url" class="broadGroups" onClick="goThere(this)" src="the_url" value="Film"></input>
基本上,我想在與class =“ CategoryTreeLabel”相同的標記內創建所有href鏈接的數組,然后我想創建一個函數goThere(),該函數將打開一個帶有good_url URL的新窗口。 需要從我們從標簽中獲取的鏈接列表中隨機選擇the_url,該鏈接在文檔中具有“ CategoryTreeLabel”類。
每個按鈕都應該調用goThere(this)函數,並從我們創建的數組中選擇一個隨機URL,檢查它是否具有http://(它總是會重定向到沒有它的頁面,但我還是把它留在了里面很有趣),然后打開該頁面
jQuery函數的返回值是一個類似數組的對象,也就是說,它具有.length
屬性,可以使用array-style []
括號表示法進行訪問,因此您實際上不需要創建單獨的數組變量太。
我注意到您的按鈕似乎是針對不同類別的鏈接,例如體育或電影,因此您的意圖可能是“體育”按鈕將選擇與體育相關的隨機鏈接,而“電影”按鈕將選擇與電影相關的隨機鏈接,相關鏈接? 如果是這樣,您可以讓每個按鈕將類別傳遞到goThere()
函數,然后從該類別中選擇一個隨機鏈接。 像這樣:
function goThere(category)
{
// assume that the parameter is the class name for links
// in the desired category
var $myLinks = $("a." + category);
// check if there are any matching links
if ($myLinks.length === 0) {
alert("Sorry, no links in the " + category + " category.");
return;
}
var url = fixURL($myLinks[ Math.floor(Math.random()*$myLinks.length) ].href);
var new_window = window.open(url,"new_window",
"menubar, resizeable. location, toolbar, status, scrollbars");
}
然后,您將設置錨標記,使其類名稱具有適當的類別,如下所示:
<a class="sports" href="http://somesportssite.com">Super sports</a>
<a class="film" href="http://moviesRus.com">Movies</a>
<a class="film" href="http://animationplus.com">All about animation</a>
<a class="sports" href="http://football.com">Football site</a>
<a class="sports" href="http://skydiving.com">Let's jump!</a>
和相關的按鈕將是:
<input type="button" value="Sports">
<input type="button" value="Film">
您可以像設置onclick="sports"
一樣設置內聯處理程序,也可以在document.ready處理程序中執行類似以下操作,以使用單個jQuery .click()
調用.click()
假設相應的類名/ category是按鈕標簽的小寫版本:
$('input[type="button"]').click(function() {
goThere(this.value.toLowerCase());
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.