2014-11-03 117 views
0

我试图为wordpress创建一个图像滑块插件。我希望它做的一件事是让图像在点击时全屏显示。设置将变量附加到HTML onClick事件的jQuery函数

为了避免页面加载所有全尺寸图片,我想在用户点击图片时调用jquery ajax函数。

所以插件知道什么样的形象来加载,该功能将为该图像WordPress的附件ID的参数,这样的链接看起来像:

<a href='javascript:void(0)' onClick='fullscreen(123)'><img src="previewimage" /></a> 

...这将基本上只是意味着获得图像与ID 123并显示它。

jQuery的我有没有工作看起来是这样的:

(function($) { 

$.fn.fullscreen = function(id) { 
    stage = $('#template-to-place-image-in'); 
    stage.css('display', 'block'); 

     $.ajax({ 
      // a bunch of ajax parameters that get the image with the requested id and then place it into the template 
     }); 

    event.preventDefault(); 
    return false; 
}; 

}(jQuery)); 

主要问题是,当我尝试点击预览图像,JavaScript控制台给了我一个错误说:

Uncaught ReferenceError: fullscreen is not defined 

我对javascript和jquery很新,所以我猜这是一个非常简单的语法问题,但我不知道我在做什么错。如果有人可以帮助它会是真棒:)

回答

0

With $.fn您正在为jQuery创建一个额外的函数。所以你可以通过使用$(mySelector).fullscreen()来访问他。

在这种情况下,不需要创建jQuery函数。 使用下面的JavaScript代码:

(function($) { 

    window.fullscreen = function(id) { 
     var stage = $('#template-to-place-image-in'); 
     stage.css('display', 'block'); 

      $.ajax({ 
       // a bunch of ajax parameters that get the image with the requested id and then place it into the template 
      }); 

     event.preventDefault(); 
     return false; 
    }; 

}(jQuery)); 
+0

这将导致相同的'undefined'错误,因为'fullscreen'是私有的'函数($){}'。要在'onClick'属性中使用fullsreen,它必须声明为** global **。要么删除包装'(函数($){}(jQuery))',那么必须在** jQuery之后包含**代码。或者将'window.fullscreen = fullscreen;'设置为最后一行以使其成为全局。 – 2014-11-03 12:11:18

+0

@MartinErnst:谢谢!忘记了。我更新了答案 – 2014-11-03 12:27:04

+0

优秀 - 现在有效。感谢你们俩! :) – 2014-11-03 12:48:05

相关问题