Inline jQuery; select relative to script tag

2019-04-06 02:24发布

问题:

This is a bit goofy, as its counter-intuitive to liberating markup of Javascript, however I'm going to ask anyways.

Given this snippet:

<p>Hello</p>
<script type="text/javascript">
    $(document).ready(function(){
        $('relative-selector').next('p').hide();
    });
</script>
<p>World</p>

This snippet would target the <script> tag itself with this "relative selector", and .next('p').hide() would result in <p>World</p> being hidden.

Does there exist a "relative selector", or means of targeting the script tag a given snippet resides within?

The answer I'm looking for (given such one exists) would not require the use of an id attribute, or any such identifying attributes; it would work with an arbitrary number of <script> tags in a given document, regardless of position in the DOM tree.

I've seen some strange implementations that don't use $(document).ready(), instead relying on the fact that the remaining markup has not loaded, using $('script:last') or some such concoction. This isn't what I'm after though; I'd like to .bind() some handlers to elements relative to the binding script snippet (typically after, which is why the unloaded markup trick won't work)

$(this) simply targets the document object due to the ready handler. $(this) outside of load-deferred handlers targets window.

I've already nearly accepted that this probably isn't possible, however I'm sure if any solution exists, its floating about in the minds of fellow SO users.

回答1:

You can probably insert a temporary element using

document.write("<div id='temp' style='display: none'></div>")

and then using that to find the next element using jQuery. Afterwards you can remove the element.

$("#temp").next("p").doSomething();
$("#temp").remove();

Another option would be to build on the technique you suggested of the partialy loaded document to retrieve a reference to the tag, but to use it only on load:

(function() {
    var thisScript = $('script:last');
    $(function() {
         thisSctipt.next("p").doSomething();
    });
})();


回答2:

I do not think you can make a relative selector for the containing script tag.

There's a jQuery selector for script tags: script[type*=javascript], you could try adding a class or id attribute to the

element(s) you want to hide and then write your jQuery selector to select all

elements right after a script tag and check for each of those

elements if they contain the class indicating they should be hidden.

It's been a while since I've worked with jQuery so you'll have to excuse me, but I cannot provide you with a code sample at this time.