Red*_*ant 1 javascript jquery jquery-selectbox drop-down-menu
我正在使用此站点/脚本中的jQuery链式选择下拉框.我把它放在侧边栏中,它在主页上工作正常,但它不适用于帖子页面,调试器指出了这个错误.
Uncaught TypeError: Object function ()
{for(var a=[];this.length;)a.push(this.splice(Math.random()*this.length,1));
for(;a.length;)this.push(a.pop());return this} has no method 'replace'
Run Code Online (Sandbox Code Playgroud)
它说有一个错误 escapeQuotes : function(str) {return str.replace(/([""\\])/g, "\\$1");
脚本的开头:
(function($) {
$.dynamicDropdown = {
/**
* Escape quotation marks and slashes
* @param {String} String to format
* @return {String}
*/
escapeQuotes : function(str) {
return str.replace(/([""\\])/g, "\\$1");
},
Run Code Online (Sandbox Code Playgroud)
这是我如何调用该函数.我正在使用json文件将选项文本和值拉入选定的框:
$(document).ready(function(){
$.getJSON('suggest.json', function(data){
var $select = $('#mySelectID');
$.each(data, function (index, o) {
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box2 + "|" + o.Box3);
$select.append($option);
});
$("#mySelectID").dynamicDropdown({"delimiter":"|"});
});
});
Run Code Online (Sandbox Code Playgroud)
编辑:
似乎与我刚放在网站上的随机图像旋转器存在冲突.我暂时删除了旋转器,链式选择框工作正常.这是一个显示错误的示例.而这是不随机旋转器.
Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1));
while (s.length) this.push(s.pop());
return this;
}
var picData = [
['img1','url_1'],
['img2','url_2'],
['img3','url_3'],
picO = new Array();
randIndex = new Array(); //array of random indexes
for(i=0; i < picData.length; i++){
picO[i] = new Image();
picO[i].src = picData[i][0];
picO[i].alt = picData[i][1];
randIndex.push(i);
}
randIndex.shuffle();
window.onload=function(){
var mainImgs = document.getElementById('carouselh').getElementsByTagName('img');
for(i=0; i < mainImgs.length; i++){
mainImgs[i].src = picO[randIndex[i]].src; //assign a random image
mainImgs[i].parentNode.href = picData[randIndex[i]][1];
mainImgs[i].alt = picData[randIndex[i]][1];
}
}
Run Code Online (Sandbox Code Playgroud)
在您使用的此脚本中,问题很可能出现在以下代码行中:
for (var i in parts) {
name += "[\"" + $.dynamicDropdown.escapeQuotes(parts[i]) + "\"]";
...
}
Run Code Online (Sandbox Code Playgroud)
关键是,不要使用for in循环遍历数组,因为可能有一个函数添加到数组Array.prototype中的for in循环中,只需将其更改为:
for (var i=0;i<parts.length;i++) {
name += "[\"" + $.dynamicDropdown.escapeQuotes(parts[i]) + "\"]";
...
}
Run Code Online (Sandbox Code Playgroud)
那么这将不再是那个功能.
当你添加到帖子中时,原因正是我所指出的.但是如果你仍然坚持使用for in循环,你应该检查这样的类型parts[i]:
for (var i in parts) {
if(typeof parts[i] != "string") continue;
name += "[\"" + $.dynamicDropdown.escapeQuotes(parts[i]) + "\"]";
...
}
Run Code Online (Sandbox Code Playgroud)
你有另一个for in循环相同的问题:
for (var i in options) {
option = $(document.createElement("option"))
.val($.isArray(options[i]) ? i : options[i])
.html(i)
.appendTo(select);
}
Run Code Online (Sandbox Code Playgroud)
将其更改为for (var i=0;i<options.length;i++)或添加此项:
if(typeof options[i] != "string") continue;
Run Code Online (Sandbox Code Playgroud)
到你的for循环的第一行.