I have a button
<button type="button" data-id="5" class="get_attr" >Click Me</button>
and i want to get the data-id value then i write the code
<script type="text/javascript">
$(".get_attr").on("click",function(){
var id = $(this).data("id");
console.log("id = "+id); //id = 5
});
</script>
Suppose I want this value, or do any functionality on this button
from another function
if i call function
from this code like and I want like this:
<script type="text/javascript">
$(".get_attr").on("click",function(){
updateValue(this);
});
function updateValue(this){ // it will take it as a parameter
var id = $(this).data("id");
console.log("id = "+id); //id = 5
}
</script>
You can not use 'this' becasue it is Javascript keyword
<script type="text/javascript">
$(".get_attr").on("click",function(){
updateValue(this);
});
function updateValue(abc){ // it will take it as a parameter
var id = $(abc).data("id");
console.log("id = "+id); //id = 5
}
Now its work fine...
Being this
is a reserved word, change the parameter name from this
to some other like in updateValue(thatObj)
.
$(".get_attr").on("click",function(){ updateValue(this); }); function updateValue(thatObj){ var id = $(thatObj).data("id"); console.log("id = "+id); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button" data-id="5" class="get_attr" >Click Me</button>
You cannot use a reserved keyword in your function definition. It should work with simply using another name in the definition.
<script type="text/javascript">
$(".get_attr").on("click",function(){
updateValue(this);
});
function updateValue(originalObject){ // it will take it as a parameter
var id = $(this).data("id");
console.log("id = "+id); //id = 5
}
</script>
Try this
$(".get_attr").on("click",function(){ var id = $(this).data("id"); console.log("id = "+id); //id = 5 }); $(".get_attr").on("click",function(){ updateValue(this); }); function updateValue(x){ // it will take it as a parameter var id = $(x).data("id"); console.log("id = "+id); //id = 5 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <button type="button" data-id="5" class="get_attr" >Click Me</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.