簡體   English   中英

將變量傳遞給JQuery函數

[英]Passing variables to a JQuery Function

 <script type="text/javascript"> $(document).ready(function(){ $("input[type='button']").click(function(){ var radioValue = $("input[name='gender']:checked").val(); if (radioValue) { alert("Your are a - " + radioValue); } }); }); </script> <label> <input type="radio" name="gender" value="male" />Male</label> <label> <input type="radio" name="gender" value="female" />Female</label> 

我想編輯上面的簡單jquery腳本以接受輸入名稱(name ='gender')作為變量/參數。 我怎樣才能做到這一點。 而不是從字面上說出這個名字。

HTML:

 <label> <input type="radio" name="gender" value="male" />Male</label> <label> <input type="radio" name="gender" value="female" />Female</label> 

這個例子應該讓你開始:

 $(document).ready(function() { $("input[type='radio']").click(function() { var chkType = $('#chkType').val(); var radioValue = $("input["+chkType+"]:checked").val(); if (radioValue) { alert("Your are: " + radioValue); } }); }); 
 .flex-parent{display:flex;} .flex-child{flex:1;} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <h3>1. Click Male/Female radio buttons. Working normally BUT using a variable.</h3> <h3>2. In the input box, change "gender" to "size" and click change button, then click the Tall/Short radio buttons</h3> <div class="flex-parent"> <div class="flex-child"> <label><input type="radio" name="gender" value="male" />Male</label> <label><input type="radio" name="gender" value="female" />Female</label> </div> <div class="flex-child"> <label><input type="radio" name="size" value="tall" />Tall</label> <label><input type="radio" name="size" value="short" />Short</label> </div> </div><!-- .flex-parent --> <div> <input id="chkType" type="text" value='name="gender"' /><button>Change</button> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM