Javascript函数本身调用

I want to display a customized alert when i click a but if im logged in i want to redirect to another page. I have this.

        <div id="contentCalendar" class="col-md-3 images_1_of_4 text-center">
            <a><img onClick="show_alert();" id="rotateme" class="img-responsive img-circle center-block" src="web/images/calendaricon.png"/></a>
            <h4><a href="#">Check our last events</a></h4>

        </div>
        <div id="myalert" class="alert alert-error">
        <a href="#" class="close" data-dismiss="alert">&times;</a>
        <strong>Error!</strong> You must be logged in to see our calendar.
        </div>  
        <script>    
        $('#myalert').hide(); 
        //What happen if you want to enter the events without loggin.
        var logged_in = <?php echo ($logged_in); ?>;
        function show_alert()
        {
            if(logged_in==true)
            {
                window.location="timeline.php";
            }
            else
            {
                $('#myalert').show();
            }
        }
        </script>

For some reason works like a charm when Logged_in is true and i get redirected. But when im logged out it just doesnt show the alert even if i didnt press the button at all.

Any ideas?

Always, again, always, run everything you embed in JS through json_encode:

var logged_in = <?php echo json_encode($logged_in); ?>;

When you simply echo a falsy value in php, it echoes nothing, thus breaking your javascript.

You need to wrap the script in some kind of event. Try :

  $(document).ready(function () {
  var logged_in = <?php echo ($logged_in); ?>;
        function show_alert()
        {
            if(logged_in==true)
            {
                window.location="timeline.php";
            }
            else
            {
                $('#myalert').show();
            }
        }
});

Try this line:

var logged_in = <?php echo $logged_in ? 'true' : 'false'; ?>;

This assumes that the php code outputs the Boolean correctly. Viewing the page source will allow you to see if it is outputted correctly.

Now looking at the JavaScript code.

Move the onclick to the anchor and cancel the click event

<a href="#" onclick="show_alert(); return false"><img ....

A better solution is to dump the inline event handler.

Attach the click unobtrusively and use preventDefault to cancel the click.

HTML:

<a href="timeline.php" class="calendar"><img ....

JavaScript

var logged_in = <?php echo ($logged_in); ?>;
$("a.calendar").on("click", function (e) { 
    if(!logged_in) {
        e.preventDefault();
        $('#myalert').show();
    }
});