检索一个值,而不对id名称进行硬编码
Retrieve a value without Hard coding the id name
目标:
从输入框中检索值,而不是用javascript对文本"item2"进行硬编码。
问题:
有可能做到吗?如果是,如何?
https://jsfiddle.net/2q7fwvq2/2/
<p>Example list:</p>
<input id="test" value="item2">
<ul><li id="item1">Coffee (first li)</li><li id="item2">Tea (second li)</li></ul>
<p>Click the button to get the HTML content of the previous sibling of the second list item.</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> Whitespace inside elements is considered as text, and text
is considered as nodes.</p>
<p>If you add whitespace between the two li elements, the result will be "undefined".</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("item2").previousSibling.innerHTML;
document.getElementById("demo").innerHTML = x;
}
</script>
您可以访问带有类名的输入标签,也可以使用以下javascript将其作为html的第一个输入标签:
document.getElementsByTagName("input")[0].value;
和jQuery:
$("input").first().val();
您可以访问具有给定id的输入标签:
var x = document.getElementById(document.getElementById('test').value).innerHTML;
function myFunction() {
var x = document.getElementById(document.getElementById('test').value).innerHTML;
document.getElementById("demo").innerHTML = x;
}
<input id="test" value="item2">
<ul>
<li id="item1">Coffee (first li)</li>
<li id="item2">Tea (second li)</li>
<li id="item3">Chai (third li)</li>
</ul>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- difference between '$(<%= DDL.ID %>) & $('
- 使用Javascript获取所选选项ID
- 根据id将json数组组合为一个json数组
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 对id以某个字符串开头的元素进行计数
- 如果元素's的ID以数字开头
- 通过id和class属性获取元素
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- 如何为地理编码请求传递ID
- AngularJS - 动态 DOM 操作,无需在控制器中硬编码 dom id
- 铬错误或编码错误?目标页面中的锚/ID 链接不起作用
- 如何使用 sql 行 id 使用使用 JSON 编码数据定义元素
- 对要用作html有效路径的路径进行编码的最佳方式“;id”;或“;name”;标签
- 检索一个值,而不对id名称进行硬编码
- 创建像getels(id)这样的函数是错误的编码约定吗?
- 任何用于编码复杂标识符的标准函数,如html元素id/class/name
- 我应该避免在id属性中编码信息吗?
- 将 ID 编码的 JS 效果更改为类
- 将 id “1_0xr__abc@xyz.com__abc@uvw.com__054gg” 转换或编码为数字 srtri