I´m having a normal JavaScript-function and want to use the Variable (myVar) also in my jQuery Code - is this possible? and how?:
<a onclick="showtitle(abctitle);" href="#">Testlink</a>
<script>
function showtitle(myVar) {
myTitle = myVar;
}
$(document).ready(function() {
alert(myTitle); //I would like to alert "abctitle"
};
</script>
I´m having a normal JavaScript-function and want to use the Variable (myVar) also in my jQuery Code - is this possible? and how?:
<a onclick="showtitle(abctitle);" href="#">Testlink</a>
<script>
function showtitle(myVar) {
myTitle = myVar;
}
$(document).ready(function() {
alert(myTitle); //I would like to alert "abctitle"
};
</script>
Share
Improve this question
asked Apr 24, 2013 at 12:34
MarcMarc
191 silver badge3 bronze badges
5
- what is this I dont even – Bill Commented Apr 24, 2013 at 12:39
- why is that variable in your HTML code in the first place? – Alnitak Commented Apr 24, 2013 at 12:40
- how you get myTitle on your page load without click on a – The Mechanic Commented Apr 24, 2013 at 12:42
- @Sarfaraz with the current code, he can't – Alnitak Commented Apr 24, 2013 at 12:43
- i think he has to improve his code first – The Mechanic Commented Apr 24, 2013 at 12:44
3 Answers
Reset to default 3Firstly, don't mix DOM0 inline event handlers with jQuery. Separate your markup and your logic.
If you use a data-
attribute you can put your variable's content in your HTML, and then extract that in the event handler:
<a id="test" data-foo="mytitle" href="#">Testlink</a>
and then:
$(document).ready(function() {
$('#test').on('click', function() {
alert($(this).data('foo'));
}
});
In this code the alert
won't appear until the link is actually clicked on, of course.
I believe @Alnitak has a great answer. But if you are just looking to solve the question you asked, wrap abctitle in single quotes and make myTitle
a global variable:
<a onclick="showtitle('abctitle 2');" href="#">Testlink</a>
<script>
myTitle = "abctitle";
function showtitle(myVar) {
myTitle = myVar;
}
$(document).ready(function() {
alert(myTitle); //I would like to alert "abctitle"
});
</script>
Also, your document ready function was missing its closing parenthesis )
Working example here: http://jsfiddle/CbhxY/
UPDATE
Working example on jsfiddle did not work so well. Try this: http://jsbin./ohedab/1/
The JS Bin example also adds the alert
call in the showtitle function.
you can do with this
function showtitle(abctitle){
alert(myTitle); //I would like to alert "abctitle"
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745356950a4624176.html
评论列表(0条)