Javascript使用变量设置属性

Javascript set attribute using variable

本文关键字:设置 属性 变量 Javascript      更新时间:2023-09-26

我不确定这里的语法,但到目前为止我的代码是。。。(注意:我通过了"#begmile"、"#endmile"answers"#totmile"形式的三个文本框的id,我想将"totmile"复选框的值设置为endmile-bigmile)

function subtract(begmile, endmile, totmile){
y=$(begmile).attr('value');
z=$(endmile).attr('value');
y=z-y;
$(totmile).setAttr('value',???);

}

到目前为止,我不确定我在这里的语法是否正确,但假设是(y正确设置为endmile-begmile,我如何使用setAttr将totmile的值设置为y的值?

这是正确的语法:

var href = 'http://cnn.com';
$(selector).attr('href', href);

您的最后一行没有调用正确的方法:

$(totmile).setAttr('value',???);

应该是:

$(totmile).attr('value',???);

例如

$(totmile).attr('value', y);//set the value to the variable "y"

您也可以调用.val();来轻松获取字段的值,或者调用.val(newValue);来设置值。

还要注意,如果"y"answers"z"的值实际上并不代表数字,那么会得到一个奇怪的结果。

value属性指的是文本框的默认值,而不是当前值。当前值存储在value属性中。

function subtract(begmile, endmile, totmile) {
    document.getElementById(totmile).value =
      document.getElementById(endmile).value - document.getElementById(begmile).value;
}

这也消除了对jQuery的需求,因为JavaScript大锤对于这项工作来说太多了。为了确保它有效,只需在向函数传递ID时删除#即可。