jQuery插件 - 使用变量外部函数

时间:2013-12-26 04:38:52

标签: javascript jquery

我有一个jQuery插件的函数,可以遍历一些图像。

//load images
function ImageSettings(config, fileNames) {

    //loop through the array in the second argument
    for (var x = 0; x < fileNames.length; x++) {

            //create image
            $("<img />").attr({
                id: fileNames[x],
                src: config.imgDir + fileNames[x] + config.imgFormat,
                title: fileNames[x] + " layout"
            }).appendTo("#" + config.imgContainer);
    }


};

继续我的插件,我需要在无序列表项中传递图像attr ID,但我的变量位于我的函数中,名为fileNames。

所以如果使用:

  $(config.sidebar).append('<ul>' + fileNames + '</ul>');
//I get a string like: home, about, contact but I need it to be styled in a list item

如果我使用split方法删除“,”那么我得到一个未知的方法拆分。 那么,是否可以将函数和变量传递到内部?比如说,所以我解决了未知的方法?

 $(config.sidebar).append('<ul>' +
ImageSettings(fileNames[x]).each(function() {
  $( this ).wrap( "<li>" ); 
+ '</ul>');

我想过使用像$('img')。attr('id')这样的东西,然后在列表项中设置这个样式,但是因为我的页面上会有几个图像,但并非所有图像都会加载而不是全部都会需要包装在列表项中。因此我想在函数中使用我的变量。谢谢。

1 个答案:

答案 0 :(得分:1)

您的代码似乎有点费解。 this会解决您的问题吗?

以下是代码:

var config = {
    "imgContainer": "imgContainer",
    "sidebar": "ul",
    "imgDir": "",
    "imgFormat": "jpg"
};
var fNames= [/* list of file names */];

function ImageSettings(fileNames) {
    //loop through the array in the second argument
    for (var x = 0; x < fileNames.length; x++) {
        var fname = fileNames[x];
        //create image
        $("<img />").attr({
            id: fname.substr(fname.lastIndexOf("/"+1, fname.length)),
            src: config.imgDir + fname + "."+config.imgFormat,
            title: fname.substr(fname.lastIndexOf("/"+1, fname.length)) + " layout"
        }).appendTo("#" + config.imgContainer);

        $(config.sidebar).append('<li>' + fname + '</li>');
    }
}
ImageSettings(fNames);