检索没有硬编码id名称的值

时间:2015-11-06 12:17:08

标签: javascript jquery html html5

目标:
从输入框中检索值而不是对文本进行硬编码" item2"在javascript。

问题:
有可能吗?如果是,怎么样?

  

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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以使用其类名访问输入标记,也可以使用javascript将其作为html的第一个输入标记:

document.getElementsByTagName("input")[0].value;

和jQuery:

$("input").first().val();

答案 1 :(得分:0)

您可以使用给定的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>