[英]Adding to a div that is nested inside another div using Javascript
[英]Accessing a nested value inside of a div using JavaScript
我在運行一些基本的JavaScript時遇到問題。 我剛開始使用JavaScript,所以還沒有完全掌握它。 我要實現的是在表單/表的div中返回選項選擇器的值。
我正在利用Google跟蹤代碼管理器將數據發送到Google Analytics(分析),並嘗試使用內置的自動事件偵聽器以及自定義JavaScript宏。
基本上,有三個不同的選擇器,它們都有不同的值。 這些都在表格中,在<select>
中帶有選擇項。
如何使用JavaScript從三個不同的選擇器中獲取選擇的值?
我正在努力解決的問題是,選擇器本身沒有ID可以將它們分開,但是父元素atleast具有唯一的div ID。
我將嘗試對其外觀進行可視化處理:
<form>
<div id="selection1">
<table ... >
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</table>
</div>
<div id="selection2">
<table ... >
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</table>
</div>
<div id="selection3">
<table ... >
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</table>
</div>
</form>
我如何能夠從不同的選項中檢索和選擇的值? 我已經嘗試過了,它的工作原理是:
function () {
var option = document.GetElementsByTagName("select")[0].value;
return option;
}
但是然后我需要為您可以從中選擇的三個不同選擇中的每一個進行設置。 我只是不夠聰明,無法弄清楚如何編寫JavaScript來計算某人在三個不同選項中選擇的內容並返回其值。
好吧,首先讓我們改進您的代碼:
<option value="xy">This is some random text</option>
一般的做法:
var selects = document.getElementById("myselect");
var selectedValue = selects.options[selects.selectedIndex].value;// will gives u "xy"
var selectedText = selects.options[selects.selectedIndex].text;// gives u "This is some random text" but you should not use this<br><br>
您可能要使用類似的方法:
var selects = document.querySelector("#selection1 select"); //This will return the first <select> inside the specified id. You may need to adjust that selector...
var selectedText = selects.options[selects.selectedIndex].text;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.