2011-06-27 161 views
-4

我有一個JavaScript函數。顯示/隱藏在onChange中。我想轉換它在jQuery中,如何做到這一點。如何將javascript函數轉換爲jquery

Javacript功能

function assocWindowOnLoad() 
     { 
      var option=document.getElementsByName("select_id"); 
      document.getElementById('conent1').style.display='none'; 
      document.getElementById('conent2').style.display='none'; 
     } 

function assocWindowOnChange(val) 
    { 
      //if user select option Select from drop down 
      if(val=='') 
      { 
       //alert("Please Select option from the dropdown"); 
      assocWindowOnLoad(); 
      } 
      else 
      { 
       //Show or hide piece of code depending on user input 
       document.getElementById('conent1').style.display=(val=='no')?'none':'block'; 
       document.getElementById('conent2').style.display=(val=='no')?'block':'none'; 
      } 
     } 

HTML代碼

<body onLoad="assocWindowOnLoad();"> 
<select name="select_id" id="select_id" onChange="assocWindowOnChange(this.value);" > 
      <option value='' selected="selected">Select</option> 
      <option value='no'>1st Option</option> 
      <option value='yes'>Second Option</option> 
</select> 

<div id="conent1" class="hide"> 

<p>some content</p> 

</div> 

<div id="conent1" class="hide"> 

<p>some content</p> 

</div> 

<div id="conent2" class="hide"> 

<p>some content</p> 

</div> 
</body> 

回答

1

使用jQuery的hide() and show()方法..

function assocWindowOnLoad()  { 
    $('#conent1').hide(); 
    $('#conent2').hide(); 
} 

function assocWindowOnChange(val){ 
    //if user select option Select from drop down 
    if(val==''){ 
     //alert("Please Select option from the dropdown"); 
     assocWindowOnLoad(); 
    }else{ 
     //Show or hide piece of code depending on user input 
     if(val=='no'){ 
      $('#conent1').hide(); 
      $('#conent2').show(); 
     } 
     else{ 
      $('#conent1').show(); 
      $('#conent2').hide(); 
     } 
    } 
} 
+0

yeah ............. :) – Vivek

0

你可以嘗試這樣的事情

$(document).ready(function(){ 

    // To hide the element 
    $("YOUR_SELCTOR").click(function() 
    { 
     $("ELEMENT_TO_BE_HIDE").hide("slow"); 
    }); 

    // To show the element 
    $("YOUR_SELCTOR").click(function() 
    { 
     $("ELEMENT_TO_BE_HIDE").show("slow"); 
    }); 


}); 

您可以使用toggle()來代替hideshow

0
toggleDisplay = function() { 
    if($('#select_id').val()=='no'){ 
    $('#conent1').hide(); 
    $('#conent2').show(); 
    } else { 
    $('#conent1').show(); 
    $('#conent2').hide(); 
    } 

} 
$(document).ready(function() { 
    toggleDisplay(); 
    $('#select_id').change(function() { 
     toggleDisplay(); 
    }); 
}) 
+0

感謝您的代碼,我的目標是不使用onChange等任何js函數。一切都必須由jquery控制。 – vivek

+0

@vivek查看更新後的答案 –

0
<script> 
$("select #myselectid").change(function() { 
    var str = ""; 
    var value = $(this).val(); 
    if (value == 'yes') { 
    $('conent1').hide(); 
    $('conent2').show(); 
    } 
    else { 
    $('conent1').show(); 
    $('conent2').hide(); 
    } 
});