2014-11-03 110 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