Jquery 的 on 方法出现问题

标签 jquery events methods

嘿,我有一个表单,里面有一些选择框,我使用一个小而简单的 jquery 插件来帮助我设计它们的样式。

$.fn.extend({
customSelect : function(options) {

  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
  return this.each(function() {

        var outerClass = options.customClass,
            innerClass = options.customClass_inner;

        var currentSelected = $(this).find(':selected');
        var html = currentSelected.html();
        if(!html){ html=' '; }
        $(this).after('<span class="customStyleSelectBox"><span class="customStyleSelectBoxInner">'+html+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
        var selectBoxSpan = $(this).next();
        var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));         
        var selectBoxSpanInner = selectBoxSpan.find(':first-child');
        selectBoxSpan.css({display:'inline-block'});
        selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
        var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
        $(this).height(selectBoxHeight).change(function(){
        selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
        }); 
  });
  }
}
});
$('select').customSelect();

没关系,它工作得很好,问题是我还有一个按钮,如果你点击广告越来越多的选择框,你想要多少就多少。(别介意为什么:P) 这些选择框也是在 jquery 的帮助下创建的,因此我将其动态添加到 dom 中。

所以我的问题是这些新的选择框当然不会继承样式,我知道这是因为我稍后将它们添加到dom中,但是我可以借助 on 方法让它们继承吗?

谢谢您的帮助!

最佳答案

您只需再次调用

$('select.newSelect').customSelect();

将新选择添加到 DOM 后。请小心添加一个特殊的类,以便您的 customSelect() 代码仅适用于新添加的元素,否则您会附加事件两次。或者,您可以概括该插件,以便它不会两次附加事件,但这会更困难(提示使用 .data() )

为了避免做奇怪的事情,如果你调用 $('select.newSelect').customSelect(); 你可以这样做

  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
  return this.each(function() {

  if($(this).data('customSelectApplied') !== ''){
        // whe already attached the custom functionality here
        return;
    }else{
        //continue as usual
        $(this).data('customSelectApplied', true);

关于Jquery 的 on 方法出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10331915/

相关文章:

jquery - CSS 在特定情况下删除空格

c# - 事件处理程序抛出对象引用错误

java - 使用数组计算偶数/奇数的平均值

java - Java 8 中是否可以使用方法引用来定义/实现方法?

jQuery 文本框更改事件

javascript:页面加载后执行该功能的最佳方式

javascript - 生成随机值,保留返回值的历史记录

c# - 如何在 C++/CLI 中将事件处理程序分配给事件?

javascript - 使用 javascript (jquery) 找出 iframe 的 window.location.href 何时发生更改

python - 如何将自己的方法添加到内置的 str 类型中?