按钮onclick()事件不应该打开链接

This may sound weird, but I want to have a button with a link that does not open when the users clicks it:

<a href="http://mysite.nl/test.php?value=snow"> click</a>

I want to do this because this link has PHP values to recreate the page. The button is on with a new background colour.

I can't just use

document.body.style.backgroundColor='Snow'

because the page auto reloads and I want the colour to stay 'snow' even when the page reloads.

Can this be done? Are there better ways to permanently change the style by the click of a button?

You can use php SESSION for this

$_SESSION['color']='snow';

and take the value from from session by each reload. And use preventDefault() for prevent the link redirection by using javascript

I suggest using hidden fields and have the background as the value, Then with javascript you grab the value of the hidden field

If you want it to be permanent for a user, you should store it in your database. You should do that by making a call to your server. You can use ajax for that. Using jquery's ajax's function makes it really easy.

http://api.jquery.com/jQuery.ajax/

You should post to your sever using ajax and change the background color in the database. If you do not want to have to refresh the page, you should then use javascript to change the background color.

Again, jQuery makes this really easy... $('element').css('background-color','color');

Do you try create a simple < button onclick='javascript:myfunction(); return false;'>test < /button> ?

and you implement what you want inside 'myFunction()'

You can use localStorage.

Assign the value in hidden field color. Just pass the color in url http://mysite.nl/test.php?value=red.

HTML

 <form>
      <a id="change-bg" href="#"> click</a>
      <input type="hidden" name="color" value="<?=(!empty($_GET['value']) ? $_GET['value'] : '')?>"/>
    </form>

JQUERY

<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function() {
        if (typeof(Storage)!=="undefined" && typeof localStorage.bgColour !== 'undefined' ) {
            $('body').css({'background' : localStorage.bgColour});
        }
        $('#change-bg').click(function(){
            $('body').css({'background' : $('[name="color"]').val()})
            localStorage.bgColour = $('[name="color"]').val();
            return false;
        });
    });
</script>