我使用JQuery blur()方法从'select'元素的选项中提取值,但由于某种原因,它总是拉取selectedIndex = 0的值而不是我选择的selectedIndex。
这是 - > JSFiddle< - 由于某种原因,第一行工作正常(长度),但其他行都不起作用。'
在任何文本框中键入一个数字(除了第一个'长度')然后从相邻的SELECT框中选择一个项目,然后单击远离SELECT
您将看到代码始终在每个SELECT元素中选择option = 0的值。并且它也无法将我的'data-hid'属性识别为数字(请参阅textbox元素中的html)
有人可以帮忙吗?我现在已经坚持了一天。
**此外,由于某些原因,这仅适用于JQuery 1.7.2而不适用于1.9版本(它不喜欢'选项:选定'代码,是否有人知道该代码段如何符合最新版本?
$('select').blur(function() {
//Get the value of the option chosen
var unit = $(this + 'option:selected').val();
//If the selectedIndex is 0 then focus on the select and make the user chose a unit.
if ($(this).prop('selectedIndex') == 0) {
$(this).focus();
return;
} else {
//Remove the 'd' in front of the 'select' element ID and you will have the ID of the textbox
var txt = "#" + $(this).attr("id").substr(1);
//Get the numerical value of the textbox
var mval = parseFloat($(txt).val());
if ($(txt).attr('data-hid') == "OFF") {
var hid = mval / unit;
$(txt).attr('data-hid', hid);
alert("hid = " + hid + "\nmval = " + mval + "\nunit = " + unit);
}
else
{
var hid = $(txt).attr('data-hid');
var newtxt = hid * unit;
$(txt).val(newtxt);
}
}
main();
});
答案 0 :(得分:2)
答案 1 :(得分:1)
这一行错了:
//Get the value of the option chosen
var unit = $(this + 'option:selected').val();
应该是:
var unit = $(':selected', this).val();
要了解原因(除了查看jQuery文档之外),请在blur
函数下面尝试此行:
console.log(this + 'option:selected'); //outputs something like [object HTMLSelectElement]option:selected
你可以做类似的事情:
console.log('#' + $(this).attr('id') + ' option:selected'); //outputs something like #mySelectBox option:selected
但是现在我们只是有点荒谬了:D ......但也许它可以帮助你理解jQuery选择器如何工作至少= 0]
Torsten's回答是真正做到这一点的正确方法
答案 2 :(得分:1)
如果您想获取选择的值,即所选选项的值,正确的方法是:
$(this).val(); // Inside the .blur "this" points to your select
然后,不是检查所选索引是否为0,而是检查值是否为空,如果是空返回,则该人员已从您的选择中选择了有效值。
另外,在你的小提琴html上第一个选项是“选中”,你不必放置那个关键字使第一个选项表现为默认选项,如果没有选择则选择第一个选项。
此外,您确定要在模糊时触发此事件吗? wouldnt .change更适合你的目的。根据您的描述,“工作流程”是在输入中键入数字,然后在选择中选择一个单位。用户选择值后立即更改触发器,仅当选择字段失去焦点时才会触发模糊触发。