简体   繁体   中英

How to make html and javascript code reusable simultaneously?

I just put my navbar html code to a separate reuse-able using jQuery plug-in. The html rendered well which is absolutely no problem.

However, the javascript code I wrote and put in a external/imported script file concerning the navbar dropdown content stopped working now?? @ @

This is the story:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script>
    $(function(){
        $('.navbar').load('reuseable.html');
    });
</script>
</head>
<body>

  <nav class="navbar">
   ...
  </nav>

...at the end of file: before body closing tag, I imported the js:

<script src="js/main.js"></script> 

the js contains functions affecting navbar:

$(function() {
$('#dropbtn').mouseenter(function() {
    $('.dropdown-content').css('display', 'block');
});
$('#dropbtn').mouseleave(function(){
    $('.dropdown-content').css('display', 'none');
})

$('.dropdown-content').mouseover(function() {
    $('.dropdown-content').css('display', 'block');
});
$('.dropdown-content').mouseleave(function() {
    $('.dropdown-content').css('display', 'none');
});


//side-nav
$('#dropbtn-side').mouseover(function(){
    $('#dropdown-content-side').css('display', 'block');
});
$('#dropdown-content-side').mouseleave(function(){
    $('#dropdown-content-side').css('display', 'none');
});

});

My hunch is that because your event listeners are looking for the elements before they have been added to the DOM they are not being found and no listener is being set. If you rewrite it using .on and delegating off the document then the dynamically added content should be properly listened to:

$(function() {
    $(document).on('mouseenter', '#dropbtn', function() {
        $('.dropdown-content').css('display', 'block');
    });
    $(document).on('mouseleave', '#dropbtn', function() {
        $('.dropdown-content').css('display', 'none');
    })

    $(document).on('mouseover', '.dropdown-content', function() {
        $('.dropdown-content').css('display', 'block');
    });
    $(document).on('mouseleave', '.dropdown-content', function() {
        $('.dropdown-content').css('display', 'none');
    });


    //side-nav
    $(document).on('mouseover', '#dropbtn-side', function() {
        $('#dropdown-content-side').css('display', 'block');
    });
    $(document).on('mouseleave', '#dropdown-content-side', function() {
        $('#dropdown-content-side').css('display', 'none');
    });
});

I didn't make any other improvements/changes-- you also could consider leveraging a better parent to delegate from, depending on what your markup looks like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM