admin管理员组文章数量:1325713
I'm getting syntax errors while trying to add an if/else statement the onclick attribute. What is the syntax for this?
<div onclick="var element = $('#selector'); if (element.val() == 'something') { alert('hello'); } else { alert('goodbye'); } ">
Click here
<input type="hidden" id="selector" value="something" />
</div>
...and yes, I must have this javascript in the onclick attribute (can't move this to a function).
I'm getting syntax errors while trying to add an if/else statement the onclick attribute. What is the syntax for this?
<div onclick="var element = $('#selector'); if (element.val() == 'something') { alert('hello'); } else { alert('goodbye'); } ">
Click here
<input type="hidden" id="selector" value="something" />
</div>
...and yes, I must have this javascript in the onclick attribute (can't move this to a function).
Share Improve this question edited Sep 28, 2010 at 20:43 Andrew asked Sep 28, 2010 at 20:08 AndrewAndrew 239k195 gold badges530 silver badges718 bronze badges 02 Answers
Reset to default 5.val()
is a jQuery method. You want to access the value
property of the DOM element.
if (element.value == 'something') {
Or create a jQuery object if you have jQuery loaded:
if ($(element).val() == 'something') {
If you took that approach, you could always use a jQuery selector:
if ($('#selector').val() == 'something') {
Javascript DOM elements do not have a val()
function. (Are you thinking of jQuery?)
Change .val()
to .value
.
If you are thinking of jQuery, you can write if ($('#selector').val() == 'something')
.
本文标签: JavaScript How to execute an ifelse statement in an onclick attributeStack Overflow
版权声明:本文标题:JavaScript: How to execute an ifelse statement in an onclick attribute? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742195479a2430999.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论