我有一个按钮,我正在更改其值和名称,单击后在警报中显示相同的值。当我使用 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/