不能使用jQuery选择器获取属性

Can not use jQuery selector to get attribute

本文关键字:获取 属性 选择器 jQuery 不能      更新时间:2023-09-26

我想知道为什么我不能使用jQuery选择器来获得这样的属性:

<input type="text" class="inputText" value="Enter text...">
console.log($('.inputText').getAttrbute('value'));

chrome开发工具显示我的错误信息:"Uncaught TypeError: $(…)。getAttrbut不是一个函数".

但是原生JavaScript方式是可以的:

var input = document.body.children[0];
console.log(input.getAttribute('value')); //Enter text...

可以在jQuery对象上使用val(),也可以在JavaScript对象上使用getAttribute。

console.log($('.inputText').val());

你也可以通过在jquery对象后面使用[0]来获取JavaScript对象。

console.log($('.inputText')[0].getAttrbut('value'));

要获取任何属性,您可以使用attr(),但如果您正在寻找输入值,请使用val()

jQuery方法是.attr():

console.log($('.inputText').attr('value'));

您正在寻找jQuery的attr方法。

问题是$('.inputText')给你的jquery对象不是直接dom元素。另外dom元素没有getAttrbut()属性,而是getAttribute()属性。

你可以得到它:

console.log($('.inputText').val());//recommended
console.log($('.inputText').attr('value'));
console.log($('.inputText').prop('value'));
console.log($('.inputText').get(0).getAttribute('value')); //use get() to access direct dom element.

jquery没有任何名为" getattribute "的方法。但是如果你需要访问属性,那么就像这样使用"attr"

$(".inputT").attr("AttributeName");

或者如果你想删除属性,那么使用

$(".inputT").removeAttr("AttributeName");