【问题标题】:How can I add an event observer for each element I find on the page?如何为页面上找到的每个元素添加事件观察者?
【发布时间】:2012-10-24 11:04:01
【问题描述】:

我正在使用 Prototype 编写脚本来检测 Div 下的所有选择标签,然后在每个标签上添加一个事件/观察者!

这里是找到我需要的元素的代码:

Event.observe(window, 'load', function() {
  var tab=$("product-options-wrapper").descendants();
  var attCode=[];
  var j=0;

  for (i=0;i<tab.length;i++) {
    if (tab [i].tagName =="SELECT") {
      attCode[j++]=tab[i].id
    }
  }
});

我有我需要的所有 ID。 如何为每个观察者添加一个观察者(更改时)?

$(id).on("change", function(event) {
  alert(id+"__"+$(id).value);
});

【问题讨论】:

    标签: javascript prototypejs dom-events


    【解决方案1】:

    Prototype 支持开箱即用的事件委托。 Event.on 采用可选的第二个选择器参数。所以在你的情况下:

    $("product-options-wrapper").on('click', 'select', function(event, element) {
    
      // This callback will only get fired if you've clicked on a select element that's a descendant of #product-options-wrapper
      // 'element' is the item that matched the second selector parameter, in our case, the select.
    
      ....
    
    });
    

    该参数可以是任何 CSS 选择器字符串:

    $('my-element').on('click', '.some-class', function(event, element) { ... });
    

    也请查看Element.select。这会将原始问题中的代码压缩为基本上一行:

    $("product-options-wrapper").select('select');
    

    这似乎有点令人困惑,因为您的选择器字符串是“选择”(您希望所有 SELECT 元素都位于#product-options-wrapper 下)。你也可以这样做:

    $$('#product-options-wrapper select');
    

    它们都返回匹配元素的数组。

    HTH

    【讨论】:

      【解决方案2】:

      您只需要 div 上的点击处理程序(换句话说,使用event delegation

      var tab = $("product-options-wrapper");
      tab.on('click',function(e){
        e = e || event;
        if ( /^select$/i.test((e.target || e.srcElement || {}).tagName) ){
          //do stuff
        }
      });
      

      【讨论】:

      • ok thx,如何更改 SELECT 的 ID 和 VALUE??
      【解决方案3】:

      应该可以。如果您需要更多帮助,请发布您的 html 或更好的 jsfiddle

      $(function(){
          $('#product-options-wrapper select').on("change", function(e) {
             alert(id+"__"+$(this).val());
          });
      });
      

      我猜你忘记了 product-options-wrapper 开头的. 来表明它是一个类?还是真的是标签?

      【讨论】:

      • “product-options-wrapper”是 DIV 的 ID。
      • 第一个代码检查这个 div 并在其中找到所有
      • 我更新了我的代码。它将在窗口加载时执行,为您的 div 内的每个选择添加一个更改处理程序,并且如果您更改其中一个选择字段,则应该发出警报。而且代码更少。你想达到什么目标?
      • 我在运行它时得到了这个错误! Erreur : TypeError: $("#product-options-wrapper select") is null
      • 问题被标记为 [prototypejs],而不是 [jquery]
      猜你喜欢
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      相关资源
      最近更新 更多