Javascript 如何在多个引导选项卡上运行.js文件?
我有一个运行JavaScript文件的页面,该文件从JSON文件中提取数据。JS在页面上附加了一个div。当前JS在$(document.ready)上运行 我已经使用Bootstrap将选项卡添加到页面中,我希望在不同的选项卡上运行相同的JS代码,但是为每个选项卡访问不同的JSON文件 我是否需要将JS封装到一个新函数中,并使用tab click事件调用该函数?只是想寻求一点帮助,找到最好的方法 编辑以添加代码:Javascript 如何在多个引导选项卡上运行.js文件?,javascript,jquery,html,json,twitter-bootstrap,Javascript,Jquery,Html,Json,Twitter Bootstrap,我有一个运行JavaScript文件的页面,该文件从JSON文件中提取数据。JS在页面上附加了一个div。当前JS在$(document.ready)上运行 我已经使用Bootstrap将选项卡添加到页面中,我希望在不同的选项卡上运行相同的JS代码,但是为每个选项卡访问不同的JSON文件 我是否需要将JS封装到一个新函数中,并使用tab click事件调用该函数?只是想寻求一点帮助,找到最好的方法 编辑以添加代码: <!DOCTYPE html> <html lang = "e
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="quiz.json"></script>
<script src="Quiz.js"></script>
<link rel="stylesheet" type="text/css" href="Assets/bootstrap-3.3.5-dist/css/bootstrap.min.css">
</head>
<body role = "document">
<div class="container" >
<div class="row">
<div class="col-md-12">
<h2>Presidential Trivia</h2> </hr>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#tab1" aria-controls="home" data-toggle="tab">Home</a></li>
<li role="presentation"><a href="#tab2" aria-controls="profile" data-toggle="tab">Profile</a></li>
<li role="presentation"><a href="#tab3" data-toggle="tab">Messages</a></li>
</ul>
</div>
</div>
<!-- tab sections -->
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="row" style="height:100px">
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div id='main' class="panel panel-info">
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="min-width:3%; width:0%">
</div>
</div>
<div id='buttons'>
<button id='prev' class='btn'>Back</button>
<button id='next' class='btn pull-right'>Next</button><br><br>
<button id='restart' class='btn'>Start Over?</button>
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
<div class="tab-pane" id="tab2">
<div class="row" style="height:100px">
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div id='main' class="panel panel-info">
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="min-width:3%; width:0%">
</div>
</div>
<div id='buttons'>
<button id='prev' class='btn'>Back</button>
<button id='next' class='btn pull-right'>Next</button><br><br>
<button id='restart' class='btn'>Start Over?</button>
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
</div>
<div class="tab-pane" id="tab3">Tab 3 content....
</div>
</div>
</div>
<script src="Assets/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
</body>
</html>
下面是一个关于如何在显示前使用“show.bs.tab”事件更改当前活动窗格的内容。检查内联注释以获得更详细的解释
//下面我刚刚给出了动态更改内容的示例,您可以这样想
//在此处更改或分配URL而不是内容
//例如:var url=“sample/sample”,并在开关情况下更改此选项
var Homejson=“一些家庭内容”;
var Profilejson=“一些配置文件内容”;
var MessagesJson=“一些消息内容”;
var SettingsJson=“某些设置内容”;
var body=“”;
函数getTabContents(目标)
{
//根据传递的目标更改此常用函数中的url内容,或者
//可以根据所选的选项卡在此处传递url,并按如下方式编写ajax
/*$.ajax({
url:urlpassedasparameter,
数据:必要数据,
成功:功能(结果){
在此处返回内容
},
错误:函数(){
在这里返回一些消息
}
});*/
var-content=“”;
交换机(目标){
案例“家”:
内容=Homejson;
打破
案例“简介”:
content=Profilejson;
打破
案例“信息”:
content=MessagesJson;
打破
案例“设置”:
内容=设置;
打破
违约:
打破
}
返回内容;
}
$(文档).ready(函数(){
//调用documentready上的函数,并将第一个面板作为默认面板传递
body=getTabContents(“主目录”)
$('#home').html(body);//将更改内容的html分配给特定选项卡窗格
});
$('a[data toggle=“tab”]”)on('show.bs.tab',函数(e){
//此方法非常重要,下面的e.target指的是当前元素,它等于“this”
var target=$(e.target).attr('aria-controls')//新激活的选项卡
//从目标元素获取任何数据,并使用它更改url或内容
body=getTabContents(目标);
//再次从函数中获取内容
$(“#”+target).html(正文);
//作为html添加到正文中。
})
...
...
...
...
如果您提供JS、HTML、JSON等,我们可以更好地将其包装成一个函数,并根据单击的选项卡传递一个参数,您可以使用该参数区分单击了哪个选项卡。。如果你在这里发布一些代码,我们可以给你一些更好的想法。谢谢,我添加了JS、HTML和JSON。谢谢!我开始用这个,但我还是新的,所以我需要继续用这个,以使它的工作。我添加了我目前正在使用的代码,不确定这是否有帮助。我在每个选项卡上获得了不同的json
,但老实说,您需要做很多更改,在每个选项卡中保持id
的唯一性,在单击next
、previous
等时参考适当的控件。。。或者只需为外部的所有选项卡分别保留一个div
、next
和不同的控件,然后相应地重置或保持每个选项卡的状态。正如我所说,有很多工作要做。。但这绝对是一个好问题:)非常感谢。这很有帮助。随时。。快乐编码…)
$(document).ready(function(){
var allQuestions;
var userName ;
var counter = 0;
var main = $("#main");
var userInputs = [];
var numCorrect = 0;
var fadeSpeed = 700;
var next = $("#next");
var prev = $("#prev");
var restart = $("#restart")
//ajax call to json file
function getData(myUrl, cb) {
$.ajax({
type: "GET",
url: myUrl,
success: function(content) {
var myData = content;
cb(null, myData);
},
error: function() {
cb(true);
}
});
}
getData('quiz.json', function(err, data) {
if(err) {
console.log('There was an error getting quiz data. Try again later or contact the admin.');
return;
}
//store data as a global variable
allQuestions = data;
//load first question
createQDiv();
})
if (counter == 0) {
$("#prev").hide();
}
//click handler for Next Question button
next.click(function() {
var selection = $("input[name=answer]:checked").val();
if (selection != undefined) {
choose();
fadeQuestion();
setTimeout(function() {
clearLast();
counter++;
moveProgress();
prev.show();
createQDiv();
}, fadeSpeed);
} else {
alert("You must select an answer to proceed.")
};
});
//creates question element
function createQDiv() {
//$("#prev").hide();
var question = $("<div id='question' class='panel-body'></div>").fadeIn(fadeSpeed);
main.append(question);
if (counter < allQuestions.length) {
displayNext();
} else {
displayScore();
}
};
//fade out question element
function fadeQuestion() {
$("#question").fadeOut(fadeSpeed);
};
//clears question element
function clearLast() {
main.empty();
};
//adds question and answers to question element
function displayNext() {
restart.hide();
var qPara = $("<p>" + allQuestions[counter].question + "</p>")
$("#question").append(qPara);
createRadios();
addPrevSelection();
};
//creates radio buttons for each choice
function createRadios() {
var choices = allQuestions[counter].choices;
//var formElement = $("<form></form>");
//$("#question").append(formElement);
for (i = 0; i < choices.length; i++) {
$("#question").append($("<input type='radio' name='answer' value='" + i + "'>" + choices[i] + "<br>"));
};
};
//checks user's answer choice and stores in array
function choose() {
var input = $("input[name=answer]:checked").val();
userInputs[counter] = input;
};
//create function for checking user's answers vs number correct. output = number of correct answers
function correctAns() {
for (i = 0; i < allQuestions.length; i++) {
if (userInputs[i] == allQuestions[i].correct) {
numCorrect++;
};
};
};
//create 'last page' for displaying user's score
function displayScore() {
next.hide();
prev.hide();
correctAns();
var score = (numCorrect / allQuestions.length);
//var encouragement;
var scoreElement = $("<p>You got " + numCorrect + " out of " + allQuestions.length + " correct.</p>");
$("#question").append(scoreElement);
/*if(score == 1){encouragement = " Perfect Score. You are amazing.";}else if(0.5<score<1){encouragement = "Better luck next time!";}else{encouragement = "Repeat after me: 'Do you want fries with that?'"};
scoreElement.append(encouragement);*/
restart.show();
};
prev.click(function() {
if (counter > 0) {
fadeQuestion();
setTimeout(function() {
clearLast();
counter--;
moveProgress();
createQDiv();
addPrevSelection();
choose();
}, fadeSpeed);
//Cristina: what if user changes input and then hits back? It isn't kept, only logged on the next button.
}
else {
prev.hide();
}
});
function addPrevSelection() {
var selection = userInputs[counter];
var radioSelected = $("input[value='" + selection + "']");
//alert(radioSelected);
radioSelected.prop("checked", true);
};
restart.click(function() {
counter = 0;
next.show();
userInputs = [];
numCorrect = 0;
clearLast();
moveProgress();
createQDiv();
});
function moveProgress(){
var newWidth = ((counter)/allQuestions.length)*100;
$(".progress-bar").css("width", "" + newWidth + "%");
};
});
[{
"question": "How many presidents were members of the Whig party?",
"choices": ["Four", "Three", "Two"],
"correct": 0
}, {
"question": "Who was the first president to be impeached?",
"choices": ["Andrew Jackson", "Andrew Johnson", "Warren Harding"],
"correct": 1
}, {
"question": "How many presidents died during their presidency?",
"choices": ["Four", "Six", "Eight"],
"correct": 2
}, {
"question": "How many presidents had no party affiliation?",
"choices": ["One", "Two", "Three"],
"correct": 0
}, {
"question": "Who was the only president to serve two non-consecutive terms, making him both the 22nd and 24th president?",
"choices": ["John Quincy Adams", "William Howard Taft", "Grover Cleveland"],
"correct": 2
}]