一旦按钮被创建,无论如何,我可以添加一个链接或使用window.location方法是这样的:`window.location ='nextpage.html?foo = number'。目前,我有这个如何添加一个链接到动态创建的按钮?
var typeValue = location.search;
var typeStringValue= typeValue.replace("?type=","");
var containers = typeValue.replace("?type=multi","");
var containersValue = parseInt(containers);
var sampleLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
function createButton(buttonName){
var buttonDivBlock = document.getElementById("sampleSets");
var buttonElement = document.createElement("input");
buttonElement.setAttribute("type","button");
buttonElement.setAttribute("name",buttonName);
buttonElement.setAttribute("value","Sample Set"+" "+buttonName);
buttonElement.setAttribute("id",buttonName);
buttonDivBlock.appendChild(buttonElement);
// document.getElementById(sampleLetter[i]).setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
}
function setButtons(numberOfContainers){
for(i=0;i<numberOfContainers;i++){
createButton(sampleLetter[i]);
}
}
window.onload = function(){
setButtons(containersValue);
}
但document.getElementById("'"+sampleLetter[i]+"'").setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
返回NULL值。
可能受骗者/相关的问题:http://stackoverflow.com/questions/789824/add-onclick-property-to-input-with-javascript,http://stackoverflow.com/questions/6909988/add-an-onclick-event-to-a-div,http://stackoverflow .com/questions/3316207/add-onclick-event-to-newly-added-element-in-javascript。 。 。请注意,“onclick”不是有效的属性,这是您的示例代码试图执行的操作。 – ernie
那么它不是我正在寻找的,因为我已经尝试过,没有成功。 :( – Ch32k0
@ernie我在其他页面上使用过它并且仍然可以工作 – Ch32k0