开发者

JavaScript: How to execute an if/else statement in an onclick attribute?

开发者 https://www.devze.com 2023-01-18 12:22 出处:网络
I\'m getting syntax errors while trying to add an if/else statement the onclick attribute. What is the syntax for this?

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 thi开发者_如何学Gos to a function).


.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').

0

精彩评论

暂无评论...
验证码 换一张
取 消