检索一个值,而不对id名称进行硬编码

Retrieve a value without Hard coding the id name

本文关键字:id 编码 一个 检索      更新时间:2023-09-26

目标:
从输入框中检索值,而不是用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>