我正在从AJAX检索数据,并按照下面的代码创建动态spans
。在代码中,我还获得了单击“应用”按钮时的跨度数据,但是当我加载网页时,它第一次运行良好,但为了获得正确的数据,我不得不再次重新加载页面。
那么如何在不重新加载数组的每次单击的情况下获取数据,并且每次单击都会先清空数组,然后将跨度的所有数据放入数组中以供进一步使用?
$(document).ready(function(){
$( "#loadingDiv" ).fadeOut("slow");
var firstLetter;
var span_array = [];
var counter = false;
$('#apply').click(function(e){
span_array=[];
console.log(span_array);
e.preventDefault();
if (day == "Select day") {
alert("Please Select the day")
}
else{
$('#link').show();
var array_dates = [];
$.ajax({
url:"/api/v1/schedule",
type: "GET",
dataType: 'json',
data:{day:day, provider: "provider 1"},
success: function(response){
// console.log(response.response.data);
if (response.response.data == null) {
}
else{
for (var i = 0; i < response.response.data.length; i++) {
$("#days_of_the_month").append("<div id='specific'><span id="+i+" class='emphasis label label-important'>"+response.response.data[i]+'</span><a class="dateEdit" id='+i+' href="#" ><i class="fa fa-edit"></i></a></div>');
}
$('.emphasis').html(function(i, h) {
return h.replace(/^(\d+)/, '<span class="hidden">$1</span>');
}).click(function() {
var number = $(this).find('.hidden').text();
console.log(number);
});
}
$('div[id^="days_of_the_month"]').each(function () {
var $this = $(this),
len = $this.find('span.emphasis').length;
for (var i = 0; i < len; i++) {
span_array.push($('#'+i).text());
}
});
console.log(span_array);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select class="select_day" id="select_day">
<option>Sunday</option>
<option>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
<option>Thursday</option>
<option>Friday</option>
<option>Saturday</option>
</select>
<button id="apply">Apply</button><br>
<a id="link" value="apply" style ="cursor: pointer; display:none;" data-toggle="modal" data-target="#exampleModalCenter">
Set Working Hours
</a><br><br>
<div id="days_of_the_month"></div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="margin: -1px;">
From: <input type="text" id="txtFromDate" />
To: <input type="text" id="txtToDate" />
<div id="errordate"></div>
<hr>
<h4>Timing Schedule</h4>
Start Time:<br>
<select id="starthour">
<option>00</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
<select id="startminute">
<option>00</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
<option>33</option>
<option>34</option>
<option>35</option>
<option>36</option>
<option>37</option>
<option>38</option>
<option>39</option>
<option>40</option>
<option>41</option>
<option>42</option>
<option>43</option>
<option>44</option>
<option>45</option>
<option>46</option>
<option>47</option>
<option>48</option>
<option>49</option>
<option>50</option>
</select>
<select id="startmeridiem">
<option>AM</option>
<option>PM</option>
</select>
<!-- <input type="text" id="starthour" style="width: 74px;" value="" placeholder="Hours" /> -->
<!-- <input type="text" id="startminute" style="width: 74px;" placeholder="Minutes" value="" /> -->
<!-- <input type="text" id="startmeridiem" style="width: 74px;" placeholder="A.M./P.M." value="" /> -->
<br>
End Time(24 Format Please):<br>
<select id="endhour">
<option>00</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
<select id="endminute">
<option>00</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
<option>33</option>
<option>34</option>
<option>35</option>
<option>36</option>
<option>37</option>
<option>38</option>
<option>39</option>
<option>40</option>
<option>41</option>
<option>42</option>
<option>43</option>
<option>44</option>
<option>45</option>
<option>46</option>
<option>47</option>
<option>48</option>
<option>49</option>
<option>50</option>
</select>
<select id="endmeridiem">
<option>AM</option>
<option>PM</option>
</select>
<div id="error"></div>
<!-- <input type="text" id="endhour" style="width: 74px;" placeholder="Hours" value="" /> -->
<!-- <input type="text" id="endminute" style="width: 74px;" placeholder="Minutes" value="" /> -->
<!-- <input type="text" id="endmeridiem" style="width: 74px;" placeholder="A.M./P.M." value="" /> -->
<hr>
<h4>Frequency</h4>
<label><input type="radio" name="modalRadioButton" id="frequency" value="every week" checked="checked"> Every Week</label>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="savedata" >Save</button>
</div>
</div>
</div>
</div>
<!-- second modal -->
<div class="modal fade" id="secondModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="margin: -1px;">
<span id="heading"></span>
<div id="data" style=" overflow-y: scroll; height: 250px;"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button class="update" id="update" type="button" class="btn btn-primary" data-dismiss="modal">Update</button>
</div>
</div>
</div>
</div>
如何解决此问题?谁能帮我解决这个问题。
谢谢。
答案 0 :(得分:1)
首先,对您现有代码的一些观察。
if (day == "Select day") { // <- `day` is not defined anywhere. this will cause an error.
alert("Please Select the day")
} else {
...
$("#days_of_the_month").append(
"<div id='specific'>" + // <- this creates a non-unique ID which may make searching for it unreliable.
"<span id=" + i + " class='emphasis label label-important'>" + // <- this span shares an ID with the `.dateEdit` span
response.response.data[i] +
'</span>' +
'<a class="dateEdit" id=' + i + ' href="#" >' + // <- this span shares an ID with the `.emphasis.label.label-important` span
'<i class="fa fa-edit"></i>' +
'</a>' +
'</div>'
);
...
$('div[id^="days_of_the_month"]').each(function() { // <- there is only ever one div that matches this, so there's no need to loop.
var $this = $(this),
len = $this.find('span.emphasis').length;
for (var i = 0; i < len; i++) {
span_array.push($('#' + i).text()); // <- which span actually gets pushed here? `.dateEdit`? `.emphasis.label.label-important`? both?
}
});
考虑到这一点,我已经自由地重组了代码,以期希望问题和解决方案更加清楚。
我强烈怀疑必须重新加载页面的原因是,您当前没有在追加新结果之前清除上一个ajax调用的结果。
$(document).ready(function() {
$("#loadingDiv").fadeOut("slow");
var firstLetter;
var span_array = [];
var counter = false;
var cachedAjaxData; // top-level variable to store the results of the ajax call.
// delegate the click handler, rather than attaching a copy to each one.
// If you need an explanation of delegated event handlers, see the accepted answer for:
// https://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on
$("#days_of_the_month").on('click', '.emphasis', function (e) {
var number = $(this).find('.hidden').text();
console.log('number =', number);
});
// turned this into a function to:
// 1. remove this distracting bit of code from the ajax call
// 2. showcase [what I think is] a more readable and reliable way of generating markup with jQuery
var makeSpecificDiv = function (num) {
var specific = $('<div />', {
id: 'specific-' + num, // concatenating `num` to ensure uniqueness
});
var spanEmphasis = $('<span />', {
id: 'emphasis-label-' + num, // adding text and concatenating `num` to ensure uniqueness,
class: 'emphasis label label-important',
});
var spanHidden = $('<span />', { // adding the hidden span here, rather than using a `replace` function to put it in
class: 'hidden',
text: num,
});
var spanDateEdit = $('<span />', {
id: 'date-edit-' + num, // adding text and concatenating `num` to ensure uniqueness,
class: 'dateEdit',
href: '#',
});
var iEdit = $('<i />', {
class: 'fa fa-edit',
});
spanEmphasis.append(spanHidden);
spanDateEdit.append(iEdit);
specific.append(spanEmphasis);
specific.append(spanDateEdit);
return specific[0];
};
// turned this into a function to:
// 1. separate this code to more easily find the problem (either here, or the ajax call itself)
// 2. make the ajax call `success` code block smaller.
var processAjaxData = function(data) {
// cache the result of the call in a variable scoped one level up;
cachedAjaxData = data;
// use a document fragment for faster element insertions
var fragment = document.createDocumentFragment();
// loop through it
data.forEach(function (num) {
var divSpecific = makeSpecificDiv(num);
fragment.appendChild(divSpecific);
// since `num` is the `.text()` of the span, just push it into the `span_array` directly.
// further, this is effectively just making a copy of the `cachedAjaxData`
span_array.push(num);
});
$("#days_of_the_month")
// .empty() // uncomment to clear the old nodes before inserting the new ones.
.append(fragment); // insert all new DOM nodes at once.
console.log('cachedAjaxData =', cachedAjaxData);
console.log('span_array =', span_array);
};
$('#apply').click(function(e) {
span_array = [];
console.log(span_array);
e.preventDefault();
var day = $('#select_day').val(); // defined `day`
if (day == "Select day") {
alert("Please Select the day");
return; // exiting function, rather than an `else` clause to limit indentation levels.
}
$('#link').show();
var array_dates = [];
$.ajax({
url: "/api/v1/schedule",
type: "GET",
dataType: 'json',
data: {
day: day,
provider: "provider 1"
},
success: function(response) {
// console.log(response.response.data);
if (response.response.data !== null) { // eliminated empty block
processAjaxData(response.response.data);
}
}
});
});
});