Javascript Jquery获取值并在span中显示
我有一个选择字段,几乎没有选项,每个字段都指定了“value”属性和名称。选择其中一个选项后,我希望其中一个填充标题,第二个填充值。标题工作正常,但我无法让它捕捉指定的“value=”asd“值 我遗漏了什么?使用以下命令:Javascript Jquery获取值并在span中显示,javascript,jquery,select,html,Javascript,Jquery,Select,Html,我有一个选择字段,几乎没有选项,每个字段都指定了“value”属性和名称。选择其中一个选项后,我希望其中一个填充标题,第二个填充值。标题工作正常,但我无法让它捕捉指定的“value=”asd“值 我遗漏了什么?使用以下命令: $(.itemclass”)。关于(“更改”,函数(){ $(.span.iclass”).text(this.options[this.selectedIndex].textContent); $(.span.impl”).text($(this.val()); });
$(.itemclass”)。关于(“更改”,函数(){
$(.span.iclass”).text(this.options[this.selectedIndex].textContent);
$(.span.impl”).text($(this.val());
});
您可以尝试使用以下代码:
$(".itemclass").on("change", function () {
$("span.iclass").text($(this).find("option:selected").text());
$("span.impl").text($(this).find("option:selected").val());
});
以下是访问所选选项的方式:
$(".itemclass").on("change", function () {
var selectedOption = $(this).find("option:selected");
$("span.iclass").text(selectedOption.text());
$("span.impl").text(selectedOption.val());
});
或者,如果您更喜欢使用DOM节点:
$(".itemclass").on("change", function () {
var selectedOption = $(this).find("option:selected").get(0);
$("span.iclass").text(selectedOption.textContent);
$("span.impl").text(selectedOption.value);
});
好吧,我做了点手脚,请原谅我的双关语 这是我想到的
$(".itemclass").change(function()
{
$("#Name").text(this.options[this.selectedIndex].textContent);
$("#Value").text(this.options[this.selectedIndex].value);
});
这是我的小提琴
这里是我找到你的解决方案的地方,请查看这个问题的答案,了解原因
尝试
$(this.options[this.selectedIndex])
而不是在DOM元素上使用.val()
。这是一个jQuery方法。改用.value
。另外,对于选项
元素,您可以使用.text
而不是.textContent
@cookiemonster将val更改为固定值。谢谢
$(".itemclass").change(function()
{
$("#Name").text(this.options[this.selectedIndex].textContent);
$("#Value").text(this.options[this.selectedIndex].value);
});