简体   繁体   中英

Onclick return confirm not working in Jquery Mobile?

I am using the simple javascript confirm code:

function test_confirm (str)
{
    str = (str == '0')? 'Are you sure?' : str

    return (confirm(str))? true : false
}

<a href="http://example.com" onclick="return test_confirm(0)">Test</a>

This usually works except when I use Jquery Mobile the OK and Cancel button both proceeds to the URL. The expected behavior is the Cancel button should not proceed to the URL.

ie, I use Jquery Mobile by adding the following in the html head :

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>

Is there anything I should be aware of to make the javascript confirm() function work in Jquery Mobile?


Update for Phill Pafford:

It does work on plain HTML but this is actually what I'm doing and it doesn't work after redirecting to the same page using PHP's header('location:') :

The page list contains:

<a href="list/delete/1" class="customClick" data-str="0">Delete 1</a>

<a href="list/delete/2" class="customClick" data-str="0">Delete 2</a>

The list/delete action contains something like this:

$rest->delete($id);
header('location: http://example.com/list');

As you can see after clicking the URL list/delete/1 the delete procedure will go on then redirect back to the list page. That's where it starts to not work.

As soon as the redirection happens the confirm dialog doesn't work anymore.

Does something like this work for you?

JS

$('.customClick').on('click', function() {
    var str = $(this).attr('data-str');
    str = (str == '0')? 'Are you sure?' : str;

    return (confirm(str))? true : false;
});

HTML

<a href="http://jsfiddle.net/8CDc5/" class="customClick" data-str="0">Test</a>​

I had the same problem, appears like "return false;" was not stopping propagation and the link was followed anyway. Solved it by explicitly stopping propagation before returning false.

function test_confirm (e, str)
{
    str = (str == '0')? 'Are you sure?' : str

    if (!confirm(str)) {            
        e.stopPropagation();
        return false;
    }
    return true;
}


<a href="http://example.com" onclick="var e=arguments[0] || window.event; return test_confirm(e,0)">Test</a>

add this attribute

data-ajax="false"

<a data-ajax="false" href="http://example.com" onclick="return test_confirm(0)">Test</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM