选择脚本标签之前的元素 [英] Select the element right before the script tag

查看:82
本文介绍了选择脚本标签之前的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不编辑DOM的情况下选择下面代码中的第一个input(如果需要,则使用jQuery)?

How would you select the first input in the code below without editing the DOM (using jQuery if needed)?

<input type="text"/> <!-- The element I want to select -->
<script>
    // Select the input above
</script>
<input type="text"/>

请注意,在此代码示例之前和之后,输入和脚本标签的数量未知,因此$("input:eq(1)")之类的解决方案将不起作用.

Please note there is an unknown number of inputs and script tags before and after this code sample, thus solutions like $("input:eq(1)") won't work.

棘手的部分是选择执行当前JavaScript的script标记之前的input.

The tricky part is to select the input placed right before the script tag from which the current JavaScript is being executed.

不需要问我为什么我也想这样做,这纯粹是为了实现它的美,如果可能的话,我想这样做而不必在输入中添加随机id.

No need to ask me why I want to do this either, that's purely for the beauty of it, I want to do it without having to add random ids to my inputs if that's possible.

修改
这就是大多数答案无法使用的原因: http://jsfiddle.net/2WqfP/

Edit
Here's why most of the answers won't work: http://jsfiddle.net/2WqfP/

推荐答案

脚本始终在加载时运行,因此正在运行的<script>标记始终是页面上的最后一个.使用纯JS,您可以像这样获得它:

Scripts are always run as they are loaded, so the <script> tag that's running will always be the last one on the page. With pure JS you can get it like this:

var scripts = document.getElementsByTagName('script'),
    currentScript = scripts[scripts.length - 1];

编辑:我之前弄错了这个.要在这一点上获取输入,您希望获得前面的同级,因此您可以使用上一个兄弟姐妹.另外,请参见下面有关文本节点和潜在解决方案的系统注释.

I got this wrong before. To get the input at this point, you want to get the preceding sibling, so you'd use previousSibling. Also, see thesystem's comment below about text nodes and a potential solution.

var scripts = document.getElementsByTagName('script'),
    currentScript = scripts[scripts.length - 1],
    input = currentScript.previousSibling;

您还可以使用jQuery:

You could also use jQuery:

var currentScript = $('script').last();

有了脚本后,就可以轻松获得前面的输入:

Once you have the script, you can get the preceding input easily:

var input = $('script').last().prev();

这篇关于选择脚本标签之前的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆