我正在尝试确定为什么这个脚本不起作用 - 它一直在工作,直到我添加了函数就绪元素以在运行之前加载页面 - 我想也许我没有添加正确的闭包。我是JS的新手,所以如果有人有任何想法,那就太棒了!
<script>
//a simple function used to make an ajax call and run a callback with the target page source as an argument when successful
function getSubPageSource(url, successCallback)
{
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
//when source returned, run callback with the response text
successCallback(xhr.responseText);
}
};
xhr.open('GET', url, true);
xhr.send();
}
function readyFn(jQuery) {
// Code to run when the document is ready.
//find all categories with sub categories
var categories = document.getElementsByClassName('has-subcategories');
//loop through each category
for (var ii = 0, nn = categories.length; ii < nn; ii++)
{
//use a closure to pass in a static ii
(function(ii)
{
//get element
var element = categories.item(ii);
//find id
var id = element.getAttribute('data-category');
//find url
var href = element.getAttribute('href');
if (id && href)
{
//found
getSubPageSource(href, function(data)
{
//find sub categories
//trim off everything before where id shows up first
var substrSource = data.substr(data.indexOf('data-category="'+id+'"'));
//trim off the remaining of the category title
substrSource = substrSource.substr(substrSource.indexOf('</a>'));
//trim off where the next category is found
substrSource = substrSource.substr(0, substrSource.indexOf('home-categories-main'));
//trim off where the next category starts, leaving source of all sub categories
substrSource = substrSource.substring(0, substrSource.lastIndexOf('<a '))
//insert to main menu after the title
console.log(id, substrSource);
//create new node capable of having children
var newNode = document.createElement("span");
//insert new source into the new node
newNode.innerHTML = substrSource;
//insert new node after element
element.parentNode.insertBefore(newNode, element.nextSibling);
});
}
})(ii);
}
}
$(document).ready(readyFn);
</script>
答案 0 :(得分:0)
而不是
$(document).ready()
尝试使用
$(document).ready(function() {
})
或
$(function() {
});
答案 1 :(得分:0)
您需要将参数传递给$(document).ready()
:
$(document).ready(readyFn);
答案 2 :(得分:0)
我的代码中发现了一些错误:
第一个$(document).ready()
是一个jQuery方法。您必须先加载jQuery库,然后才能使用它。
您不只是将$(document).ready()
插入代码中。相反,如下所示,您传递一个回调函数,并在文档准备好后在该回调中放置您要执行的任何代码。它不仅会停止执行,直到文档准备就绪,就像您似乎在代码中使用它一样。
示例:
$(document).ready(function() {
// put code here that will execute after the DOM is ready
});
或者,您打算在代码中执行此操作的方式:
function readyFn(jQuery) {
// Code to run when the document is ready.
}
$(document).ready(readyFn);