当我向同一文档添加两个不同的javascript代码时,其中一个停止正常工作;单击下一个问题后,我的视窗将跟随。目前它还没有,我不知道为什么。我已经检查了变量名等,没有重复的。
这在过去发生过,我失去了一些功能,我真的希望这一点得到解释。
http://codepen.io/erayner/pen/mRrMVd (这是我的最终代码) http://codepen.io/erayner/pen/VPvLyR (这是它应该做的事情)
第一个代码
//when you click on an answer, the next answer appears
$(() => {
init();
});
function init() {
numberSections();
bindAnswerClick();
showSection(0);
}
function numberSections() {
$(".section").each((index, elem) => {
$(elem).data("index", index);
$(elem).attr("data-index", index);
});
}
function bindAnswerClick() {
$(".answer").on("click", (e) => {
selectAnswer($(e.currentTarget));
});
}
function selectAnswer($answer) {
let $section = $answer.closest(".section");
let nextIndex = parseInt($section.data("index")) + 1;
$section.find(".answer").removeClass("highlight");
$answer.addClass("highlight");
showSection(nextIndex);
}
function showSection(index) {
$(".section[data-index='" + index + "']").show();
}第二个代码
//variables for end answer
var finalAnswers = [];
var button = document.getElementById("button");
//add answer values together and find end URL for button
$(document).ready(function () {
$("a[data-value]").on("click", function (e) {
var value = $(this).attr('data-value');
finalAnswers.push(value);
e.preventDefault();
});
$(".Finalbutton").click(function () {
var store = finalAnswers;
var frequency = {}; // array of frequency.
var max = 0; // holds the max frequency.
var result; // holds the max frequency element.
for (var v in store) {
frequency[store[v]] = (frequency[store[v]] || 0) + 1; // increment frequency.
if (frequency[store[v]] > max) { // is this frequency > max so far ?
max = frequency[store[v]]; // update max.
result = store[v]; // update result.
}
}
if (result == "A")
button.setAttribute("href", "http://www.w3schools.com");
if (result == "B")
button.setAttribute("href", "http://dailydropcap.com/images/C-9.jpg");
if (result == "C")
button.setAttribute("href", "http://www.w3schools.com");
});
});发布于 2017-01-16 11:38:04
原因如下:
当单击".answer“时,将执行以下代码
$(".answer").on("click", (e) => {
selectAnswer($(e.currentTarget));
});但是当"a[data-value]“被点击时,".answer”也会被点击。因为
$(".answer").on("click", (e) => {
selectAnswer($(e.currentTarget));
});早于
$("a[data-value]").on("click", function (e) {
var value = $(this).attr('data-value');
finalAnswers.push(value);
e.preventDefault();
});所以第一个代码会被执行,但第二个不会。
您不应该使用.on('click',...语法。addEventListener要好得多。
让我们在可能的巨大区域上添加一个.addEventListener,而这些操作应该在单击之后完成。语法类似于以下内容:
area.addEventListener('click',function(e) {
if( e.taget ... ){ action 1 } else if( e.target ... ) { action 2 }and so on.
}https://stackoverflow.com/questions/41668984
复制相似问题