我的事件监听器没有触发。我在行testRun.addEventListener
内放了一个断点,但它从未到达断点。所以我认为这意味着函数永远不会执行。我似乎无法弄明白为什么。
我的HTML:
<form>
<input id="hdfs-test" type="radio" name="test-select" class="btn btn-default btn-lg">HDFS
<input id="hive-test" type="radio" name="test-select" class="btn btn-default btn-lg">HIVE
<input id="hdfs-hive-test" type="radio" name="test-select" class="btn btn-default btn-lg">BOTH
<textarea id="event-textarea" rows="8" class="form-control" placeholder="Events..."></textarea>
<input id="submit-test" type="submit" class="btn btn-default btn-lg" value="Submit">
</form>
JS:
$(document).ready(function() {
// Data to describe what kind of test
var testData = {
"timestamp": "",
"hive": 0,
"hdfs": 0,
// Contains a list of testData objects
"beacons":[]
};
var selectedTest = document.querySelector('input[name=test-select]:checked');
var testRun = document.getElementById("submit-test");
testRun.addEventListener('submit', function() {
var testType = selectedTest.id;
if (testType == "hdfs-test") {
testData["hdfs"] = 1;
testData["hive"] = 0;
} else if (testType == "hive-test") {
testData["hdfs"] = 0;
testData["hive"] = 1;
} else if (testType == "hdfs-hive-test") {
testData["hdfs"] = 1;
testData["hive"] = 1;
}
var events = document.getElementById("event-textarea").value;
// check in valid input
var eventSource = events.replace("],[","],,,,[");
// beaconLists allows users to submit --> [{beacon1}, {beacon2}, ...], [{beacon3}, {beacon4}, ...]
var beaconLists = eventSource.split(",,,,");
for (var i = 0; i < beaconLists.length; i++) {
// inspect one list in beaconLists [{beacon1}, {beacon2}, ...]
var beaconList = beaconLists[i];
try {
// list of JSON objects
var beaconObjList = JSON.parse(beaconList);
for (var j = 0; j < beaconObjList.length; j++) {
var beaconObj = beaconObjList[j];
if (beaconObj["data"] && beaconObj["application"]) {
// successful parse to find events
// describe beacon being tested
alert("yes");
var beacon = {
"app_name": beaconObj["application"]["app_name"],
"device": beaconObj["application"]["device"],
"device_id": beaconObj["application"]["device_id"],
"os": beaconObj["application"]["os"],
"os_version": beaconObj["application"]["os_version"],
"browser": beaconObj["application"]["browser"],
"beacon": beaconObj
};
// append to testData
testData["beacons"].append(beacon);
// reset beacon so we can append new beacon later
beacon = {};
} else {
// notify event isn't in the correct format?
alert("no");
}
}
} catch (e) {
// notify bad JSON
alert("failed");
}
}
alert("hi");
console.log(testData);
//$.ajax({
// type: "POST",
// url: "/test/",
// data: testData,
// success: function () {
// alert("yay");
// },
// failure: function () {
// alert("boo");
// }
//});
});
});
答案 0 :(得分:1)
尝试将其附加到表单,而不是按钮。
答案 1 :(得分:1)
testRun = document.getElementById("submit-test")
这是按钮,而不是表单。您需要提交form
而不是button
本身。除非你想测试点击...
然后你需要
testRun.addEventListener('click', function(){...});
虽然我仍然建议点击submit
,以防用户点击ENTER
而不是点击提交按钮。