2013-07-12 97 views
1

一旦按钮被创建,无论如何,我可以添加一个链接或使用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值。

+0

可能受骗者/相关的问题: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

+0

那么它不是我正在寻找的,因为我已经尝试过,没有成功。 :( – Ch32k0

+0

@ernie我在其他页面上使用过它并且仍然可以工作 – Ch32k0

回答

1

好吧,也许我可以帮你用一个例子沿:

function getFive() { return 5;} 

callOtherFunction("stringArgument", getFive()); 

的第二个参数callOtherFunction将是5,而不是getFive功能。在许多情况下,例如添加事件监听器和AJAX代码,实际上您都希望将该函数本身作为参数传递,以便稍后调用它。但是,如果你不想打扰seperately宣称的功能,它看起来是这样的:

callOtherFunction("stringArgument", function() { return 5; }); 

为了让代码看起来更干净,可以按Enter键{和做多线功能后。

现在,所有的想法,再看看你已注释的行。你看到缺少的东西吗? (PS。对于“egging-on”格式的道歉 - 我发现如果我帮助他们找到解决方案,而不是仅仅向他们展示解决方案,人们会更好地找出答案)

+0

会试试这个,谢谢! – Ch32k0

+0

工作!非常感谢! – Ch32k0

+0

我把它扭曲了一点;)...将张贴我的答案,并给你信用! ;) – Ch32k0

0

sampleLetter变量未定义在哪里你正在尝试使用它(通过评论代码来判断)。使用刚才设置为id属性的值。

document.getElementById(buttonName).setAttribute(/* ... */); 

或者,如果你想将其设置在循环而不是在createButton功能,不添加单引号

document.getElementById(sampleLetter[i]).setAttribute(/* ... */); 
+0

对不起,我删除了他们,而我在这里粘贴代码...感谢您注意;) – Ch32k0

+0

..并没有成功:s – Ch32k0

+0

没有成功意味着'document.getElementById(sampleLetter [i])'或'document.getElementById(buttonname)'仍然为空?因为你也可能有其他问题阻止你的代码工作。找到答案的第一步是确保您通过调用“getElementById”返回一个非空元素。 –

相关问题