首页 > 解决方案 > 如果没有 getElement 方法,这个代码的简写是如何工作的,有人可以解释一下并告诉更多关于这个类比的信息

问题描述

我正在翻阅我的书,发现一段代码没有使用传统getElement的选择方法,但使用了一些速记。有人能告诉我更多关于这件事的信息吗?我对此一无所知frm.txt.value

function  show_temp(){
    var Tval=frm.txt.value;
    alert("The temp in far. is " + Tval + " degree");
}
<form name="frm">
  Enter the temp in Fahrenheit:
  <input type="text" name="txt">
  <input type="button" value="temperature" onclick="show_temp()">
</form>

标签: javascriptdomjavascript-objects

解决方案


您所指的简写与the和 the的name属性有关-这可用于引用 JavaScript 中的元素,并可用作etc的替代品。forminputgetElementById

    function  show_temp(){
             console.log(frm.txt);
         }
    <form name="frm">
            Enter the temp in Fahrenheit:
            <input type="text" name="txt">
            <input type="button" value="temperature" onclick="show_temp()">
        </form>

但是,不建议这样做 - 与 不同idname属性可以在整个页面中重复,因此frm.txt在下面的第二个片段中引用实际上会返回一个结果数组而不是单个结果(单击两者上的温度按钮进行比较)。

    function  show_temp(){
             console.log(frm.txt);
         }
    <form name="frm">
            Enter the temp in Fahrenheit:
            <input type="text" name="txt">
            <input type="text" name="txt">
            <input type="button" value="temperature" onclick="show_temp()">
        </form>


推荐阅读