[英]jQuery function only working once when jquery .load is used
我正在使用jquery .load()函数将外部.html文件加载到我的index.html页面中。
这是我的index.html:
index.html
<!doctype>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="nav"></div>
<script src="jquery/jquery.min.js"></script>
<script>
$(function() {
$("#nav").load("nav.html");
});
function changeLayout(layout) {
if(layout == '4') {
$("[class^='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-4");
} else
if(layout == '6') {
$("[class^='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-6");
}
else
if(layout == '12') {
$("[class^='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-12");
}
}
</script>
</div>
</body>
</html>
这是我正在加载的nav.html文件:
nav.html
<div id="subnav" class="container">
<div class="row">
<div class="btn-wrapper">
<div class="layout">
<button onclick="changeLayout('4');">Layout1</button>
<button onclick="changeLayout('6');">Layout1</button>
<button onclick="changeLayout('12');">Layout1</button>
</div>
</div>
</div>
</div>
我的问题是,上面的changeLayout函数仅能“一次”运行,然后我需要重新加载整个页面才能使其再次运行。
为什么会发生这种情况,如何解决此问题?
您需要在type="button"
添加type="button"
,当前您的buttons
似乎正在submitting
页面。
也不需要按钮中的href
属性。
<button type="button" onclick="changeLayout('4');">Layout1</button>
<button type="button" onclick="changeLayout('6');">Layout1</button>
<button type="button" onclick="changeLayout('12');">Layout1</button>
将您的changelayout
函数移至nav.html
您应该将脚本放在HTML头部分中。 只需将两个脚本标签移动到头部(标题下方),就可以了。
我猜您是用已加载的html文件替换了您的身体内容-因此您所有的JavaScript都消失了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.