2012-06-14 144 views
1

使用for循環條件動態創建單選按鈕時,單選按鈕不會創建。我下面的代碼是如何使用jquery mobile動態創建單選按鈕?

Polldetails.html

 <div data-role="content" class="pollsdetailsscreen"> 
      <p>Polls details page with radio buttons created dynamically.</p> 
     </div> 
     <div> 
      <ul id="radiopolls" data-theme="e" > 
      </ul> 
      comments:<textarea name="pollscomments" id="pollscomments"></textarea> 
      <div data-role="content" > 
       <a href="#" data-role="button" style="width: 100px;float:right">Submit</a> 
      </div> 
     </div> 

Polldetails.js

 var pollsDetails = function pollsDetails(){ 

//for(var i=0;i<4;i++) 
// { 
//var radiobutton = document.createElement('label'); 
//radiobutton.innerHTML="<input type='radio' name='hello'>hii000"; 
// $('#radiopolls').prepend(radiobutton).trigger('create'); 
// } 


for(var i=0; i<4; i++) 
    { 
     if(data.type == "poll") 
      { 
          console.log("this is polls page"); 
          //here i need to create four radio buttons dynamically based on below **data** options. 
      } 
     else if(data.type == "review") 
      { 
       console.log("this is reviews page");    
      }      
    } 
    } 



     var data = { 
     type:"poll", 
     question : "How are you?", 
     options : [{ 
      type : "radio", 
      name: "radioTest", 
      text: "Good" 
     }, 
     { 
      type:"radio", 
      name: "radioTest", 
      text: "Fine" 
     }, 
     { 
      type:"radio", 
      name: "radioTest2", 
      text: "Nice" 
     }, 
     { 
      type:"radio", 
      name: "radioTest2", 
      text: "V Nice" 
     }, 
     { 
      type:"checkbox", 
      name:"check", 
      text:"This is a check box" 
     }, 
     { 
      type:"textarea", 
      name:"comments", 
      text:"Comments Please" 
     }  
     ] 
    }; 

作爲每代碼通過檢查條件,我需要動態地創建4個單選按鈕時的條件是data.type =「民意調查」,但我無法動態創建基於代碼的單選按鈕..任何人都可以請幫我這個..........

+0

你能投票答覆上一個問題的答案嗎? –

回答

1

請注意,您無法爲單個表單值混合和匹配單選按鈕和其他輸入類型。通過給4個單選按鈕命名兩個不同的名字,你基本上創造了兩個單獨的問題,每個問題有兩個答案。我敢肯定,下面的代碼將不會產生正是你想要的,但它應該讓你遠遠不夠,你可以只調整它,因爲你需要:

if (data.type === 'poll') { 
    var poll = {}; 
    for (optionIndex = 0; optionIndex < data.options.length; optionIndex++) { 
     var option = data.options[optionIndex]; 
     if (option.type === 'radio') { 
      var fieldset = poll[option.name]; 
      if (!fieldset) { 
       poll[option.name] = fieldset = $('<fieldset data-role="controlgroup">'); 
       fieldset.append($('<legend>').html(data.question)); 
      } 

      var answerID = 'poll-answer-' + (optionIndex + 1); 
      fieldset.append($('<input type="radio" />').attr('name', option.name).attr('value', option.text).attr('id', answerID)); 
      fieldset.append($('<label>').attr('for', answerID).html(option.text)); 
     } 
    } 

    var containerElement = $('#radiopolls'); 
    for (answerSet in poll) { 
     poll[answerSet].appendTo(containerElement).trigger('create'); 
    } 
} 

如果您需要任何幫助適應它,只是問。祝你好運!

相關問題