0

我有以下基于此链接的代码

<select name="myselect" class="myselectClass" id="myselectID">
    <option data-value='{"comporder":"0"}' value="myval0">test 0</option>
    <option data-value='{"comporder":"1"}' value="myval1">test 1</option>
    <option data-value='{"comporder":"2"}' value="myval2">test 2</option>
</select>
<br>
<input type="text" id="myinput" name="webStorageInput" />
<input type="submit" id="mysave" value="Save" />

<script type="text/javascript">   
var storedText = localStorage.getItem('webStorageTestInput');
var inputBox = document.getElementById("myinput");
var saveBtn = document.getElementById("mysave");
alert(storedText);

saveBtn.onclick = function(){
var valueToSave =inputBox.value.replace(/<\/?[^>]+>/gi, '');

localStorage.setItem('webStorageTestInput',valueToSave);
};
</script>

我的小提琴

我可以通过输入字段将我输入的值存储到本地存储中,但是我希望我存储的值使用用户在 my 中选择的最后一个选项,例如,如果他们选择了 test 1,则其值为 1。

我认为这是最好的方法(使用数据值),但这不是必需的,我只是不希望它使用选项值。

我尝试的另一种方法是获取选项的索引。

<select name="mySelect" class="myselectClass" id="mySelect">
    <option value="myval0">test 0</option>
    <option value="myval1">test 1</option>
    <option value="myval2">test 2</option>
</select>
<br>
<input type="submit" id="mysave" value="Save" />


<script>
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
var saveBtn = document.getElementById("mysave");


saveBtn.onclick = function(){
    alert("Index: " + y[x].index + " is " + y[x].text);
 };
</script>

但是,如果我这样做,无论我点击什么,每次都会收到以下警报。

Index: 0 is test 0
4

1 回答 1

1

你可以试试这个,因为你正在使用jQuery

$("#mysave").on('click', function(){
    var i = $("#mySelect").prop("selectedIndex");
    var t = $("#mySelect option:selected").text();
    alert("Index: " + i + " is " + t);
});

演示

于 2012-10-24T04:26:19.357 回答