我想把一个小片段变成一个函数。但我是javascript的新手。显然我传递变量的方式或我称之为的方式有问题......
简而言之,这有效:http://jsfiddle.net/kkvbz/ 但这不是:http://jsfiddle.net/PrtD4/
问题是我需要它作为一个函数,所以我要使1版本工作。
完整摘录:
function cutandMakeslides (containerid,liperslide) {
//This is for footer slider, it rewrites 1 ul into several uls that contain 4 li max.
// get the container, useful for later too...
var container = $(containerid);
// get all available UL and LI elements...
var li_elements = container.find("> UL > LI").clone();
// remove the current content so that we can rebuild it for the slider...
container.find("> UL").remove();
// build the slider container...
var slide_container = $("<div />");
// tricky part: looping through the LI's and building each of the slides...
// first create some helpful variables...
var li_elements_per_slide = liperslide;
var li_counter = 0;
// create the first slide, with a UL to hold the LI's...
var current_li_div = $("<div />");
current_li_div.append($("<ul />"));
// loop through the LI's...
li_elements.each(function(index, element){
li_counter++;
var current_li = $(element).clone();
current_li_div.find("> UL").append(current_li);
if (li_counter % li_elements_per_slide == 0)
{
// we've hit 4 in this list, so add the slide and make
// a new one, using same code as before...
container.append(current_li_div);
current_li_div = $("<div />");
current_li_div.append($("<ul />"));
}
});
// we might have an uneven number of LI's, so we need to check for this...
if (li_counter % li_elements_per_slide != 0)
container.append(current_li_div);
} // end function cutandMakeslides
//activate function above
$(function() { cutandMakeslides(".fproductslides",3); });
有问题的部分:
function cutandMakeslides (containerid,liperslide) {
var container = $(containerid);
var li_elements_per_slide = liperslide;
}
$(function() { cutandMakeslides(".fproductslides",3); });
答案 0 :(得分:0)
从你的'有问题的部分'部分看来,你正试图传递一个类(“。fproductslides”是一个类,类以'。'开头,而Id以'#'开头)而不是Id作为你的变量名让我相信你想做...
答案 1 :(得分:0)
因此经过大量测试并将代码移动到一个小提琴后,问题似乎已经在将其移动到小提琴时解决了,因此我们认为存在轻微的拼写或语法错误...但是使用代码比较工具我无法找到任何东西......
没有任何问题部分似乎有错误:
function cutandMakeslides (containerid,liperslide) {
var container = $(containerid);
var li_elements_per_slide = liperslide;
}
$(function() { cutandMakeslides(".fproductslides",3); });
以下是工作fiddle
的副本