开发者

jQuery next() - selector

开发者 https://www.devze.com 2023-02-14 15:02 出处:网络
I have a few sets of javascript codes and divs just below them: <script type=\'text/javascript\'>

I have a few sets of javascript codes and divs just below them:

     <script type='text/javascript'>
                    jQuery(document).ready(function(){
                        jQuery(".display").something({
                        /*myfunction*/
                        });
                    });
                </script>

        <div class="display"></div>  

     <script type='text/javascript'>
                    jQuery(document).ready(function(){
                        jQuery(".display").something({
                        /*myfunction*/
                        });
      开发者_开发技巧              });
                </script>

        <div class="display"></div>      

(...)

Is there a way of selecting only the .display div after exact JS? I've been thinking about next() but it's hard to attach to document.ready ;)


You should give each <div> an id and attach handlers that way.

Javascript doesn't really care where within HTML you write it. Put all your Javascript in a script file and refer to DOM elements by className/id.


Just give each DIV a unique id, and use that id in your selector.


You could give the script tag a unique id and call next():

<script id="script-tag-1">
jQuery(function() {
  var node = $('#script-tag-1').next('.display');
});
</script>
<div><!-- content --></div>

jsFiddle: http://jsfiddle.net/SYgEX/


Everything was generated dynamically (that's why I asked how to change my JS code, WITHOUT touching DOM!).

Anyways I've found the best way.

<?php $id = rand(); ?>

 <script type='text/javascript'>
                    jQuery(document).ready(function(){
                        jQuery(".display-"<?php echo $id;?>").something({
                        /*myfunction*/
                        });
                    });
                </script>

        <div class="display-<?php echo $id;?>"></div>  

Not perfect, but it works at least (and could possibly break, but chances are really low).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号