Reputation:
How can I get the onclick event (this value change when click on div) in jQuery?
$("ul li").click(function(){
var v = $(this).val();
});
$(function(){
alert(v);
});
Upvotes: 0
Views: 4262
Reputation: 30638
as I understand that you want to change the text of a div
your div is as follow
<div>123</div>
you can do it as
<script>
$("div").click(function () {
$(this).replaceWith( "new text " );
});
</script>
EDIT you can use global variable as follow
$.mynamespace = {};
$("ul li").click(function(){
$.mynamespace.myVar = $(this).val();
});
$(function(){
alert( $.mynamespace.myVar );
});
refer How to store a global value (not necessarily a global variable) in jQuery?
Upvotes: 0
Reputation: 15197
$(function() {
var v;
$('ul li').click(function() {
v = $(this).val(); // .text() - consider
testFunction();
});
function testFunction() {
alert(v);
}
});
Your issue was variable scope, you were defining a variable only available to the click function. If you define it outside of the function it will be available to other in scope functions.
Here's a demo:
You might want to consider using .text()
instead of .val()
Upvotes: 3
Reputation: 8903
If what you mean getting the innerHTML of the div when clicked, here is a code that could help
$("div").click(function(){console.log($(this).html())})
Upvotes: 0