2016-04-29 21 views
2

這下面簡單的jQuery的演示版的時
$('.markdown-editor').convertToList();稱爲繼可分離相一致的處理下拉選擇元素,並注入到DOM
- 將每個發現的鏈接上面如何使一個jQuery插件,多選擇在每一個

建立在使用類作爲選擇$('.markdown-editor')我希望它找到每個類元素中的鏈接,並將其注入到下拉選擇元件選擇僅適用於該el EMENT。

現在,如果有多個匹配元素,它會從所有元素中找到鏈接,並在每個項目中包含整個組合列表,而不是每個項目的單獨列表。

下面的演示有2個div與類.markdown-editor

內部1區有鏈接1,2,和3。

在2區是連桿4,圖5和6

所以在兩者的div其中兩個包含鏈接1創建選擇場,2,3,4,5和6,而不是包含1-3的Div1和包含4-6的Div2。

我該如何修改這個o使每個Div selectino字段只包含在該Div內找到的鏈接?

演示 - https://jsfiddle.net/jasondavis/pbkypodh

/* use : $(selector).convertToList() */ 
(function ($) { 
    $.fn.convertToList = function() { 
     var that = this; 

     // build selection list element and add it before our selector 
     this.before(
      $('<select><option>Please select</option></select>').change(function() { 
      window.location = $(this).val(); 
      }) 
     ); 

     // iterate each link inside our selector and add it to the 
     // selection element we built above 
     this.find('a').each(function() { 
      that.prev('select').append('<option value="' + $(this).attr('href') + '">' + $(this).html() + '</option>'); 
      // hide original link 
      $(this).remove(); 
     }); 
    }; 
})(jQuery); 


$(document).ready(function() { 
    $('.markdown-editor').convertToList(); 
}); 

回答

1

要對多個元素的插件代碼工作,each()包裹插件代碼。

$.fn.convertToList = function() { 
    return this.each(function() { 
     // Plugin code here 
    }); 
}; 

這可以在jQuery's plugin development guide上看到。 從這裏

你典型的jQuery對象報價將包含任意數量的DOM元素的引用,這就是爲什麼jQuery的對象通常被稱爲集合。如果您想對特定元素進行任何操作(例如獲取數據屬性,計算特定位置),則需要使用.each()來遍歷元素。

相關問題