[英]Select tag php generated code requires javascript interaction
目前,我正在使用一段JavaScript來復制鏈接以及用戶在select標簽中選擇的選項。
我在javascript中分配的變量仍未定義。 有沒有辦法使此代碼有效? 我不希望將ID屬性與循環一起使用,除非可以將其應用到我的PHP腳本中(在該腳本中,我回顯select標記,因為我正在顯示數據庫結果,每當顯示結果時,它也會顯示一個select標簽)。 該鏈接顯示了到目前為止我所做的一個簡單示例: http : //jsfiddle.net/b31au78v/
這是我的代碼:
<table>
<tr>
<th>Name</th>
<th>Gender</th>
</tr>
<tr>
<td>Hank</td>
<td>
<select onChange="getValue()" class="ddlEval">
<option>Select an option...</option>
<option val="gender.php?=male">Male</option>
<option val="gender.php?=female">Female</option>
</select>
</td>
</tr>
<tr>
<td>Jeff</td>
<td>
<select onChange="getValue()" class="ddleval">
<option>Select an option...</option>
<option val="gender.php?=male">Male</option>
<option val="gender.php?=female">Female</option>
</select>
</td>
</tr>
</table>
<script>
function getValue() {
optVal = this.value;
if(optVal != "Select an option...")
{
window.prompt("This is the link that's going to be coppied: ", "localhost:8080/" + optVal);
}
}
</script>
我想我需要用其他東西代替“ this”,但這只是為了顯示我實際想要發生的事情。
考慮以下方法:
var optVal = selectTag.options[selectTag.selectedIndex].value;
在您的情況下( jsFiddle ):
<script>
function getValue(s) {
optVal = s.options[s.selectedIndex].value;
if(optVal != "Select an option...")
{
window.prompt("This is: ", "localhost:8080/gender.php?=" + optVal);
}
}
</script>
更改onChange事件代碼時:
<select onChange="getValue(this)"...
請注意,您還應該傳遞成員的ID /名稱,因此當某人更改第一個成員的性別時,它不會與第二個成員發生沖突。
這里有兩個問題:
沒有屬性val
它應該是value
:
<option value="none">Select an option …</option>
<option value="gender.php?=male">Male</option>
注意 :如果沒有屬性value
,則元素的值將是option
-element option
的文本 。
函數中的this
具有不同的作用域,因此它不知道名為this.value
的屬性。 但是,您可以將元素傳遞給函數,例如:
<select onchange="getValue(this);"></select>
然后,您可以得到其值,例如:
function getValue(e) {
var optVal = e.value;
if ('none' != optVal) {
window.prompt("This is the link that's going to be coppied: ", "localhost:8080/" + optVal);
}
}
演示版
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.