[英]Setting an href on click with a for loop
我正在嘗試使用正確的 href 自動填充一組按鈕。 function setLink() 沒有返回我所期望的(類似於localhost:44369/Timeline?d=2020/7/3
)。 我認為這是因為它實際上並沒有使用我的值 m[i]、d[i] 和 y[i],但我不知道如何解決它。
var curr = new Date(); // get current date
var first = curr.getDate() - curr.getDay(); // First day is set to the day of the month minus the day of the week
var last = first + 6; // last day is the first day + 6
var day = new Array(7);
day[0] = new Date(curr.setDate(first));
for (i = 1; i < 7; i++) {
//This for loop creates the time info for each day with the following loop pulls the month and date out of
day[i] = new Date(curr.setDate(curr.getDate() + 1));
}
var m = new Array(7);
var d = new Array(7);
var y = new Array(7);
for (i = 0; i < 7; i++) {
//This for loop adds the date
m[i] = day[i].getMonth() + 1;
d[i] = day[i].getDate();
y[i] = day[i].getYear();
document.getElementById("Timeline-Day" + i).innerHTML += m[i] + "/" + d[i];
document.getElementById("Timeline-label" + i).onclick = function() {
setLink();
};
function setLink() {
location.href = '"?d=" y[i] + "/" + m[i] + "/" + d[i]"';
}
}
和我的 html
<div style="margin-left:6rem;" id="timelineDiv" class="btn-group btn-group-toggle my-auto col-lg-9" data-toggle="buttons">
<label onclick="" id="Timeline-label0" class="week btn">
<span id="Timeline-Day0" class="timeline-label"></span>
<input type="radio" alt="Sunday" id="option1">
</label>
<label id="Timeline-label1" class="week btn">
<span id="Timeline-Day1" class="timeline-label"></span>
<input type="radio" name="options" alt="Monday" id="option2">
</label>
<label id="Timeline-label2" class="week btn">
<span id="Timeline-Day2" class="timeline-label"></span>
<input type="radio" name="options" alt="Tuesday" id="option3">
</label>
<label id="Timeline-label3" class="week btn">
<span id="Timeline-Day3" class="timeline-label"></span>
<input type="radio" name="options" alt="Wednesday" id="option4">
</label>
<label id="Timeline-label4" class="week btn">
<span id="Timeline-Day4" class="timeline-label"></span>
<input type="radio" name="options" alt="Thursday" id="option5">
</label>
<label id="Timeline-label5" class="week btn">
<span id="Timeline-Day5" class="timeline-label"></span>
<input type="radio" name="options" alt="Friday" id="option6">
</label>
<label id="Timeline-label6" class="week btn">
<span id="Timeline-Day6" class="timeline-label"></span>
<input type="radio" name="options" alt="Saturday" id="option7">
</label>
</div>
您的setLink
有一些有趣的格式,您需要使用字符串連接(或替代方法),但這應該可以工作
function setLink() {
location.href = "?d=" + y[i] + "/" + m[i] + "/" + d[i];
}
此外,將 function 用於onclick
只是為了調用另一個 function 並沒有什么意義:
document.getElementById("Timeline-label" + i).onclick = function() {
location.href = '"?d=" y[i] + "/" + m[i] + "/" + d[i]"';
};
最后,如果您將label
更改為a
元素,您可以直接獲取它並設置href
屬性,而不需要創建 function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.