【问题标题】:Need the class of a parent function's returned element需要父函数返回元素的类
【发布时间】:2009-10-21 19:16:42
【问题描述】:

对 jQuery 来说有点新,所以请原谅尝试正确识别事物。

我需要一个元素的 id 反映在一个包含几个函数深度的选择器中,但我不太确定如何去做。

$("input[type='file'][id^='pic_']").change(       //I need this element's id...
    function()
    {
        $("."+this.id).hide("fast",
            function()
            {
                //..to be reflected in this class selector
                $("."+this.id).attr("checked", true);
            }
        );
    }
);

提前感谢您的帮助。 :-)

【问题讨论】:

    标签: jquery function css-selectors


    【解决方案1】:

    这使用闭包将带有 id 的变量带入最内层函数的范围。

    $("input[type='file'][id^='pic_']").change(       //I need this element's id...
            function()
            {
                    var fileSelector = "." + this.id;
                    $(fileSelector).hide("fast",
                            function()
                            {
                                    //..to be reflected in this class selector
                                    $(fileSelector).attr("checked", true);
                            }
                    );
            }
    );
    

    【讨论】:

    • 我的错误,我应该更清楚一点:被更改的元素是文件输入:$("input[type='file'][id^='pic_']")。 change 被隐藏的元素是一个 div: $("."+this.id).hide 被检查的元素当然是一个复选框: $("."+this.id).attr("checked", true );我想要发生的是当用户将文件放入文件输入时,复选框及其标签(在 div 内)被隐藏,然后复选框被选中。
    • 哦,看起来您的原始代码示例应该可以正常工作。不是吗?
    • 很遗憾没有,因为 $("."+this.id).attr("checked", true);被 $("."+this.id).hide 中的函数调用,它返回该元素的 id 而不是 $("input[type='file'][id^='pic_'] 选择的元素").change,它们是不同的。
    【解决方案2】:

    事件回调中的this 变量是承载事件的DOM 元素。在更改函数回调中,这是更改的元素。因此:

    $("input[type='file'][id^='pic_']").change(
      function() {
        $(this).hide("fast",
          function() {
            $(this).attr("checked", true);
          }
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      似乎是一个变量范围的问题:

      $("#my_input").change(function() {
          var my_id = $(this).attr('id');
          $(this).hide('fast', function() {
              alert(my_id); // Will show an alert with the id from above.
              alert($(this).attr('id')); // *Should* show an alert with the same id.
          });
      });
      

      【讨论】:

      • $(this).id 无效 - 但想法是正确的 - $(this).attr('id')this.id 将是有效选项。但我认为在这里关闭绝对是正确的想法。
      • 使用变量效果很好!但我想知道是否有更清洁的方法来获取它。可能是 this.this.id 之类的东西?
      猜你喜欢
      • 2014-01-16
      • 2021-12-05
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      相关资源
      最近更新 更多