javascript - 将 li 标签值传递给文本输入

标签 javascript jquery html

嗨 我有一个 li 标签如下:

<li value="myLi" class="myLi">My element</li>

我试过这个 jquery 代码:

$(".myLi").click(function(){
    document.getElementById("mytext").value=$(this).value;
});

知道 mytext 是文本类型的输入,我如何将 li 标签的值传递给 input ,如果不可能,我如何使用 innerHTML 在两者之间传递代码li 标签。

我试过的代码不起作用 谢谢

最佳答案

不管有些人怎么说,value 确实是 li 元素的有效属性,它反射(reflect)在 value 属性中,但它必须是一个整数 ( reference ):

The value attribute, if present, must be a valid integer giving the ordinal value of the list item.
...
If the value attribute is present, user agents must parse it as an integer, in order to determine the attribute's value. If the attribute's value cannot be converted to a number, the attribute must be treated as if it was absent. The attribute has no default value.

如果您粘贴的代码只是一个快速编辑,并且您确实将使用一个整数,那么如果您没有this 包装在 jQuery 中,您的代码将正常工作实例:

HTML:

<li value="3" class="myLi">My element</li>

使用 jQuery 的 JavaScript:

$(".myLi").click(function(){
    document.getElementById('myText').value=this.value;
    // Or
    // $('#myText').attr('value', this.value);
});

如果你想使用字符串,最好坚持使用新的 HTML5 data- prefix :

HTML:

<li data-value="myLi" class="myLi">My element</li>

使用 jQuery 的 JavaScript:

$(".myLi").click(function(){
    document.getElementById('myText').value=$(this).attr('data-value');
    // Or
    // $('#myText').attr('value', $(this).attr('data-value'));
});

关于javascript - 将 li 标签值传递给文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4413710/

相关文章:

html - 溢出时隐藏元素

javascript - 如何在 jQuery.get() 中有一个进度条

javascript - nodejs 多个定时器和 cpu 使用

javascript - Bootstrap标签输入不适用于本地数据

javascript - 使用 html5draggable 防止子元素被拖动

html - 隐藏 div 之外的文本

html - 具有不同重量的字体类型

javascript - document.registerElement() 有什么优势?

javascript - SendKeys 仅将输入结束放在文本字段中

javascript - 数据表 + lengthMenu + 全部 + 服务器端处理 + 不工作