确保正确加载bootstrap-toggle js文件和css文件。专门检查它们是否在链接指向的位置,甚至使用下面列出的CDN版本:
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.0/css/bootstrap-toggle.min.css" rel="stylesheet"><script src="https://gitcdn.github.io/bootstrap-toggle/2.2.0/js/bootstrap-toggle.min.js"></script>
您的路径必须是错误的,或者您忘记了完全包含js文件,并且您应该在控制台中看到关于此的警告,因为否则代码可以正常工作。
关于动态加载的内容。
第一个元素起作用是因为在html首次加载后,会
bootstrap-toggle.min.js查找具有该属性的所有元素,
data-toggle="toggle"然后调用
.bootstrapToggle()它们以应用插件。这仅在页面加载时发生。
如果以后添加更多切换,则需要通过自己进行初始化
.bootstrapToggle()。我更新了下面的示例,以模拟动态添加切换,并说明我将采用的方法。有关更多详细信息,请参见代码中的注释。
// timeout to simulate ajaxsetTimeout(function(){ // add an element dynamically, $('.table').append('<tr><td>Testswitch0</td><td><label><input type="checkbox" data-toggle="toggle" data-on id="S2" data-size="mini"></label></td></tr>'); // now that we have dynamically loaded elements // we need to initialize any toggles that were added // you shouldn't re-initialize any toggles already present // but we also do want to have to figure out how to find the ones we added // instead, we'll destroy all toggles and recreate all new ones $("[data-toggle='toggle']").bootstrapToggle('destroy') $("[data-toggle='toggle']").bootstrapToggle();}, 2000)<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><link href="https://gitcdn.github.io/bootstrap-toggle/2.2.0/css/bootstrap-toggle.min.css" rel="stylesheet"><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script><script src="https://gitcdn.github.io/bootstrap-toggle/2.2.0/js/bootstrap-toggle.min.js"></script><div id="switchespanel"> <div > <h3 >Switches</h3> </div> <div > <table > <tr> <th>Location</th> <th>State</th> </tr> <tr> <td>Testswitch0</td> <td><label> <input type="checkbox" data-toggle="toggle" data-on id="S0" data-size="mini"> </label></td> </tr> <tr> <td>Testswitch0</td> <td><label> <input type="checkbox" data-toggle="toggle" data-on id="S1" data-size="mini"> </label></td> </tr> </table> </div></div>


