2013-10-01 34 views
0

我想創建一個jQuery插件,並將其用於頁面中的某些HTML元素。 這是我的HTML代碼:爲某些HTML元素製作jquery插件

<select class="test"> 
    <option> 
     111 
    </option> 
    <option> 
     222 
    </option> 
    <option> 
     333 
    </option> 
</select> 
<select class="test"> 
    <option> 
     444 
    </option> 
    <option> 
     555 
    </option> 
</select> 

我想用我的插件select元素。 這是我的插件樣本:

(function ($) { 
     $.fn.testplug = function() { 
      var res = ""; 
      this.children("option").each(function(){ 
       res+=$(this).text()+"#"; 
      }); 
      alert(res); 
     }; 
    }(jQuery)); 

及其使用:

$(".test").testplug(); 

現在我的方面有兩個res價值觀,其中之一應該是111#222#333#和其他應444#555#,但我有一個結果,它是111#222#333#444#555#。 我該如何獲得我想要的結果? Link to jsfiddle

回答

1

您選擇這兩個,所以你必須指定要使用哪一個

$('.test:first').testplug() //111#222#333 

$('.test:last').testplug() //444#555# 

$('select').on('change',function(){ 
    $(this).testplug(); 
}); 

,或者你可以通過每一個迴路。像這樣測試

$('.test').each(function(){ 
$(this).testplug(); 
}); 

您可以通過再列出兒童和警報在每個列表的末尾還改寫這樣的代碼,循環

(function ($) { 
     $.fn.testplug = function() { 
      this.each(function(){ 
        var res = ""; 
       $(this).children('option').each(function(){ 
          res+=$(this).text()+"#"; 
       }); 
       alert(res); 
      }); 
     }; 
    }(jQuery)); 

DEMO

+0

是的,它的工作,但我有超過2選擇元素,我也不想使用'更改'事件。 –

+0

檢查更新@SamanGholami如果你想使用你的原始代碼,你可以這樣做 '$('。test')。each(function(){ $(this).testplug(); });' – Anton

+0

是,這是正確的。坦克有很多:) –

1

你的意思是2警報在一個叫做插件功能?

$.fn.testplug = function() { 
     $(this).each(function(){ 
      var res = ""; 
      $(this).children("option").each(function(){ 
       res+=$(this).text()+"#"; 
      }); 
      alert(res); 
     }); 
    }; 
+0

謝謝你的回覆:) 你應該把res放在循環中 –

+0

哦!我的不好謝謝! – Chokchai

相關問題