创建一个可重用的jQuery函数 [英] Creating a reusable jQuery function

查看:116
本文介绍了创建一个可重用的jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是每次都重写一大块代码,而是试图将功能合并到我的工作中,但我无法使其工作。

Instead of re-writing a massive block of code each time, I'm trying to incorporate functions into my work but I'm having trouble making it work.

基本上,我选择了单选按钮,每次单击单选按钮时我都会执行一些操作。 (我实际上正在加载一个iFrame)。但是,我需要使每个单选按钮的iFrame SRC不同,所以我如何在功能内满足这个要求?

Basically, I've got a selection of radio buttons and I'm performing some stuff each time a radio button is clicked. (I'm actually loading an iFrame). However, I need to make the iFrame SRC different for each radio button so how would I cater for this within the function?

函数:

The function:

jQuery.fn.switchPreview = function () {
$('.liveDemoFrame').remove();
$('.liveDemoHand').append('<iframe class="liveDemoFrame" src="themes/src/' + themeName + '/" width="100%" height="300" scrolling="no"><p>Your browser does not support iframes.</p></iframe>');
$('.liveDemoHand').append('<div class="switchPreview"><div class="loadingPreview"></div></div>');
$('.liveDemoFrame').load(function() {
    $('.switchPreview').fadeOut();  
    $('.switchPreview').remove();   
    $('.liveDemoFrame').fadeIn();
});
return this;
}

在iFrame SRC中,我有一个名为themeName的变量。我需要这个以某种方式改变每个单选按钮。你可以在调用函数的代码中看到我试图每次声明变量的函数,但这仍然给我一个未定义的错误。

Within the iFrame SRC I have a variable called themeName. I need this to somehow change for each radio button. You can see within the code that calls the function I've tried to declare the variable each time but this still gives me an undefined error.

调用它的代码:

$('#cTheme1').click(function () { 
    $('input:radio[name=mgChooseTheme]:nth(1)').attr('checked',true); 
            var themeName = 'theme1';
            $('.liveDemoFrame').switchPreview();
});

$('#cTheme2').click(function () { 
    $('input:radio[name=mgChooseTheme]:nth(2)').attr('checked',true); 
            var themeName = 'theme2';
            $('.liveDemoFrame').switchPreview();
});

$('#cTheme3').click(function () { 
    $('input:radio[name=mgChooseTheme]:nth(3)').attr('checked',true); 
            var themeName = 'theme3';
            $('.liveDemoFrame').switchPreview();
});

我确定这是非常简单的事情,但我仍然在学习如此小的东西总是会抛出我关闭!

I'm sure this is something very simple but I'm still learning so little things always throw me off!

推荐答案

- 将函数的第一行更改为:

-Change the first line of the function to:

jQuery.fn.switchPreview = function (themeName) {

- 对于三次调用函数的每一次,确保传入参数,即:

-For each of the three times you are calling the function, make sure you are passing in the argument, i.e:

$('.liveDemoFrame').switchPreview(themeName);

这篇关于创建一个可重用的jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆