javascript - javascript 和 jquery 的不同行为

标签 javascript jquery html

我有一个按钮,我正在更改其值和名称,单击后在警报中显示相同的值。当我使用 jQuery 时,它工作正常,但当我使用带有 JavaScript 函数的调用函数时,它工作正常,函数值在前 View 中没有改变,但在警报值中正在改变,这完全奇怪。

这是演示

JavaScript

function change() {
  if ($(this).attr('name') == 'first') {
    $(this).attr('name', 'second');
    $(this).attr('value', 'second');
    alert('new name ' + $(this).attr('name'));
  } else {
    $(this).attr('name', 'first');
    $(this).attr('value', 'first');
    alert('new name ' + $(this).attr('name'));
  }
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" id="button" value="first" name="first" onclick="change()">

jQuery

$('#button').click(function() {
  if ($(this).attr('name') == 'first') {
    $(this).attr('name', 'second');
    $(this).attr('value', 'second');
    alert('new name ' + $(this).attr('name'));
  } else {
    $(this).attr('name', 'first');
    $(this).attr('value', 'first');
    alert('new name ' + $(this).attr('name'));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" id="button" value="first" name="first">

我知道我可以使用 jQuery,因为我已经包含了该库,但我非常想知道这两者之间有什么区别。

最佳答案

您需要传递 this 来更改函数,以便您可以访问该函数内的单击对象,任何元素的 .click() 事件都会自动检测 $(this) 但在函数中你需要传递它

this传递到按钮的change()函数中:

<input type="submit" id="button" value="first" name="first"  onclick="change(this)">

因此更改功能将具有:

function change(obj) {
  if ($(obj).attr('name') == 'first') {
    $(obj).attr('name', 'second');
    $(obj).attr('value', 'second');
    alert('new name ' + $(obj).attr('name'));
  } else {
    $(obj).attr('name', 'first');
    $(obj).attr('value', 'first');
    alert('new name ' + $(obj).attr('name'));
  }
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" id="button" value="first" name="first"  onclick="change(this)">

关于javascript - javascript 和 jquery 的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38329208/

相关文章:

javascript - 鼠标滚轮滚动事件

javascript - ng-tags-input 无法从自动完成中选择选项

javascript - col可调整大小的行显示 :none; and the custom anchors relating to the row to have a display:none;

javascript - 如何在 clearInterval() 之后启动一个 eggtimer?

javascript - 如何创建返回间隔为 boolean 值+输入并打印的函数(number、from、to)

javascript - 谷歌 JavaScript API : catching HTTP errors

javascript - 如何在客户端显示用户已经存在 - MongoDB

javascript - 将 "active"类添加到带有取消 slider 的单独菜单

html - CSS3 - 圆形按钮 - 圆形边(水平和垂直)

html - 需要帮助创建正则表达式或脚本以在 html 文件上运行