如何在Javascript中获取属性的值 [英] How to get the value of an attribute in Javascript

查看:146
本文介绍了如何在Javascript中获取属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此输入行,我正在尝试提取value属性的文本:

I have this input line which I am trying to extract the text of the value attribute:

<input type="text" class="card-input small-font" ng-value="paymentVia.typeDisplay" readonly="" value="Credit card">

函数getAttribute("class")正常工作,它返回card-input small-font,但是函数getAttribute("value")返回null.我也尝试过.value,但这会返回一个空字符串.

The function getAttribute("class") works fine and it returns card-input small-font but the function getAttribute("value") returns null. I tried .value as well but this returns an empty string.

有人知道为什么会这样吗?

Does anyone know why this is happening?

这是我的JS:

function() {
   var x = document.getElementsByClassName("card-input small-font");
   var payment =x[18].value;

   return payment;
}

推荐答案

元素属性是html标记的不同部分. 因此,您必须改为使用element.value.

Node values and Element Attributes are different parts of an html tag. So, you have to use element.value instead.

这是一个示例,向您展示如何从输入字段中获取valuedataattribute.

This is a an example, to show you how you can fetch value, data, attribute from an input field.

HTML输入字段.

The HTML input field.

<input type="text" id="profile" data-nationality="Eritrean" value="Simon">

和javascript.

and the javascript.

var el = document.getElementById("user-profile"); 

console.log(el.value) // Simon
console.log(el.getAttribute("id")) // profile
console.log(el.dataset.nationality) // Eritrean

这篇关于如何在Javascript中获取属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆