简体   繁体   中英

Bootstrap Dropdown Select Value Not Working

I have a simple dropdown like this:

<div class="btn-group">
  <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
    Dropdown <span class="caret"></span>
  </a>
  <ul class="dropdown-menu">
    <li><a href="#">Choice1</a></li>
    <li><a href="#">Choice2</a></li>
    <li><a href="#">Choice3</a></li>
    <li class="divider"></li>
    <li><a href="#">Choice..</a></li>
  </ul>
</div>

and JavaScript for choosing one of the options like this:

$(".dropdown-menu li a").click(function(){

  $(".btn:first-child").html($(this).text()+' <span class="caret"></span>');

});

My drop down is not working, the option I choose from the dropdown does not get chosen, and in-fact my script.js file doesnt even appear in the source whiles while I try to debug in chrome.

I initialise my script file at the top of my html file like this

<script type="text/javascript" src="source/script.js"></script>

what am I doing wrong ?

You need to run your code when document is ready:

from jQuery :

$( document ).ready(function() {

or

$(function() {

If you run your code before the document is ready your code cannot work because the elements like $(".dropdown-menu li a") are not yet in the document.

So wrap your code in the document ready.

     $(function () {
        $(".dropdown-menu li a").click(function(){

            $(".btn:first-child").html($(this).text()+' <span class="caret"></span>');

        });
    });

There appears to be nothing wrong with your code (I have a working example of it here https://jsfiddle.net/xzfq7q5t/ ) however your script tag's path may be wrong.

What does your file structure look like? In other words, where does your script.js file live in relation to your html page? Is it in the same folder? Is it in a 'source' folder?

<script type="text/javascript" src="source/script.js"></script>

The above is saying, go to my current folder, then go inside the source folder, then look for script.js

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