【问题标题】:Travel to outer component until reaching the one that has a specific attribute移动到外部组件,直到到达具有特定属性的组件
【发布时间】:2016-12-21 20:01:08
【问题描述】:

示例 html 代码(看起来很奇怪,但我的目的是表明外部组件可以是任何东西)

<div>
    <div/a/p/.. myAttribute="123">
        <p>
            <a>
                <script type="text/javascript">
                    jQuery.ajax({url: "local.host?attribute= "});
                </script>
            </a>
        </p>
    </div/a/p/..>
</div>

我想要的是,从内部脚本中,在触发 ajax 调用之前,我想前往外部父组件,直到我可以到达具有 myAttribute 的组件。然后我将 myAttribute 的值填入我的 url 为"local.host?attribute= 123"

我找到了最接近的 JQuery,但它需要提前知道组件类型。

感谢任何帮助。 非常感谢。

【问题讨论】:

  • 你知道如何获取正在运行的&lt;script&gt; 元素的父元素吗,因为你的问题中没有这个元素?如果你这样做了,那么closest 应该与this approach 一起使用。
  • jQuery.ajax({beforeSend: function() {};})

标签: javascript jquery html


【解决方案1】:

我认为'*[myAttribute]' 会做得很好。

$(el).parents('*[myAttribute]');

以当前脚本为目标。你可以使用

document.currentScript;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div>
    <div/a/p/.. myAttribute="123">
        <p>
            <a>
                <script type="text/javascript">
                     var self = document.currentScript,
                         e = $(self).closest('*[myAttribute]'),
                         attrVal = (e.attr('myAttribute') );
                         console.log( attrVal );
                    // commented 
                    // jQuery.ajax({url: "local.host?attribute="+attrVal });
                </script>
            </a>
        </p>
    </div/a/p/..>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2018-05-22
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多