开发者

Combining document ready scripts?

开发者 https://www.devze.com 2023-01-14 20:41 出处:网络
I\'m using a simple show-hide script on various IDs. The issue is as it stands right now each is a seperate JS that calls the document ready function via jQuery.

I'm using a simple show-hide script on various IDs. The issue is as it stands right now each is a seperate JS that calls the document ready function via jQuery.

Is there a way to combine this into one more flexible script or at least into one script in some form or another. Thank you so much for your time in advance!

Below is an example:

<script type="text/javascript">
$(document).ready(function () {
    $("#loadDummy7").hover(

    function () {
        $("#dummy7").show();
    }, function () {
        $("#dummy7").hide();
    });
}); 
</script> 开发者_如何学C
<script type="text/javascript">
$(document).ready(function () {
    $("#loadDummy8").hover(
    function () {
        $("#dummy8").show();
    }, function () {
        $("#dummy8").hide();
    });
});    
</script>


You can combine it into a single script like this:

$(function(){
  $("[id^='loadDummy']").hover(function() {
    $("#" + this.id.replace('loadD', 'd')).toggle();
  });
});

This uses the attribute-starts-with selector to get all id="loadDummyXXX" controls and finds the element to toggle with the corresponding dummyXXX ID. An easier way would be to use classes and find it relatively, for example if your markup was like this:

<div class="dummyWrapper">
  Stuff
  <div class="dummy" style="display: none;"> More Stuff</div>
</div>

You could do it like this, much cleaner:

$(function(){
  $(".dummyWrapper").hover(function() {
    $(this).find(".dummy").toggle();
  });
});
0

精彩评论

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