在控制台上获取$('button')。attr(“value”)返回undefined

时间:2016-12-08 08:57:16

标签: javascript jquery attributes

我正在尝试构建一个计算器,但我在开始时遇到了问题。 我在attr('value')按钮上检索未定义。

这是代码

<button value="8" class="">8</button>

var input = '';
$("button").click(function(){
   input = $("this").attr("value");
   console.log(input);  
});

我无法弄明白为什么......

3 个答案:

答案 0 :(得分:2)

$("this")更改为$(this)this不应该是字符串),它应该有效:

var input = '';
$("button").on('click', function(){
   input = $(this).attr("value");
   console.log(input);  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="8" class="asdas">8</button>

答案 1 :(得分:1)

$(this) $(&#34; this&#34;)不同。

$(&#34;此&#34;)会将其视为元素选择器$("element")。 where it选择具有给定标记名称的所有元素。在您的情况下,它将找到元素this。这在DOM中不可用。

&#13;
&#13;
var input = '';
$("button").click(function(){
input = $(this).attr("value");
console.log(input);  
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="8" class="">8</button>
&#13;
&#13;
&#13;

仅供参考:我建议您使用.val()代替.attr(),因为 attr(...)只在开始时获取对象值(创建html时)。 val()获取对象的属性值,该值可以多次改变。

答案 2 :(得分:0)

使用普通的javascript this.value

var input = '';
$("button").on('click', function(){
   input = this.value;
   console.log(input);  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="8" class="asdas">8</button>

相关问题