2011-01-26 106 views
2

當用戶從下拉菜單中選擇任何一個選項時,Web應用程序中會出現一個下拉菜單,我必須生成一個文本框和複選框。我已經在下拉菜單上實現了onSelect,並且我調用了一個函數,它實際上調用了添加文本的函數,但我需要與文本框一起生成複選框。在JavaScript中獲取多個元素

我試着調用一個更多的功能,但這不起作用我也嘗試使用「& &」即使這是行不通的,我試圖調用函數內的函數,即使這是行不通的。我該怎麼做呢?

這是代碼

<SCRIPT language="javascript"> 
function add(type) { 

    //Create an input type dynamically. 
    var element = document.createElement("input"); 


    //Assign different attributes to the element. 
    element.setAttribute("type", type); 
    element.setAttribute("value", type); 
    element.setAttribute("name", type); 

    var foo = document.getElementById("fooBar"); 

    //Append the element in page (in span). 
    foo.appendChild(element); 
    //var element=document.createElement("checkbox"); 
    //var foo=document.getElementById("foobar"); 
    //foo.appendChild(element); 
    var a=1; 

    if(a==1){ 
     function add2(type) { 

      //Create an input type dynamically. 
     var chkbox = document.createElement("checkbox"); 
      //Assign different attributes to the element. 

     chkbox.setAttribute("type", type); 
      chkbox.setAttribute("value", type); 
      chkbox.setAttribute("name", type); 

      //var foo = document.getElementById("fooBar"); 
     //Append the element in page (in span). 
      appendChild(chkbox); 
     } 
    } 
} 
</SCRIPT> 
+0

告訴我們,不工作的代碼,然後我們得到告訴你爲什麼它是沒有錯的,並提出改進意見。 – Quentin 2011-01-26 07:03:56

+0

我想你正在尋找`document.createElement`,但是你可以用你自己製作一個[jsfiddle](http://jsfiddle.net)並提供鏈接,這樣我們就可以看到你在哪裏? (或至少提供一些代碼) – 2011-01-26 07:05:10

回答

2

這樣做會調用從下拉菜單中選擇參數的函數的最佳方式,但你必須生成參數在下降的各個環節下拉菜單

function fuc1(arg1 , arg2, ...) 
{ 
      //you can use these agruments to genetate attrs of input and other things 
    var input = $("<input></input>").attr({'type': 'text', 'id': someid, 'class': 'someclass' , ... }).val(someval); 
    var chbox = $("<input></input>").attr({'type': 'checkbox', 'id': someid, 'class': 'someclass' , ... }); 

    $(input).appendTo(something); 
    $(chbox).appendTo(something); 
} 

它通常以這種方式工作。如果您提交的代碼,那麼它可能有點幫助,您

更新::

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 
<script> 
function fuc1() 
{ 
     //you can use these agruments to genetate attrs of input and other things 
    var container = $("<div></div>").appendTo($('#content')); 
    var input = $("<input></input>").attr({'type': 'text'}); 
    var chbox = $("<input></input>").attr({'type': 'checkbox'}); 

    $(input).appendTo(container); 
    $(chbox).appendTo(container); 
} 

</script> 

<div id="content"></div> 
<a href="javascript: fuc1()">add</a>