Different behaviour of javascript and jquery -
i have button , changing value , name on click showing same value in alert. working fine when use jquery not when use call function javascript function value not changing in front view in alert value changing totally strange.
here demos
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">
i know can use jquery including library wanted know difference between these two.
you need pass this
change function can access clicked object inside function, .click()
event of element automatically detect $(this
) in function need pass
pass this
in change()
function in button:
<input type="submit" id="button" value="first" name="first" onclick="change(this)">
so change function have:
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)">
Comments
Post a Comment