javascript jQuery 最接近的在 IE8/9 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28041056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:19:16  来源:igfitidea点击:

jQuery's closest doesn't work in IE8/9

javascriptjqueryinternet-explorer-8

提问by DmitMedv

I have this jQuery code:

我有这个 jQuery 代码:

$(this).closest('div:has(.FIND_ME)').find('.FIND_ME').hide();

But element with class .FIND_MEdoesn't hide in IE8 and 9.

但是带有类的元素.FIND_ME不会隐藏在 IE8 和 9 中。

This question is a continuation of Search for an item with a common ancestor

这个问题是搜索具有共同祖先的项目的延续

HTML:

HTML:

<div>
    <div><!-- all div without ID -->
        <span>some text</span>
        <div>
          <span id="listener1">click here</span>
          <span>sometext</span></div>
        <div>

        <span class="FIND_ME">Result Here</span></div>
    </div>

    <div>
        <span>some text</span>
        <div id="div1">
         <div id="div2">
          <span id="listener2">click here</span>
          <span>sometext</span></div>
         </div>
        <div>

        <span class="FIND_ME">Result Here</span></div>
    </div>
</div>

回答by BenG

I was setting a variable elementto this, then later on I was calling:

我将一个变量设置elementthis,然后我打电话给:

element.closest('a')

But element was now the DOM element instead of the jQuery object. So changing to:

但是 element 现在是 DOM 元素而不是 jQuery 对象。所以改为:

$(element).closest('a')

fixed it.

解决它。

回答by DmitMedv

You're right! I don't know why, but it works now! The mistake was in an another place.

你说得对!我不知道为什么,但它现在有效!错误在另一个地方。

Thus, closest()works fine in IE 8/9. Tested on jQuery 1.6.

因此,closest()在 IE 8/9 中工作正常。在 jQuery 1.6 上测试。

回答by prampe

closest = function (target, tag) {
    if (target.parentElement == "undefined") {
        return null;
    }
    if (target.parentElement.localName == tag) {
        return target.parentElement;
    }
    return this.closest(target.parentElement, tag);
};