简体   繁体   中英

Calling a function on click via JavaScript/jQuery on button clicks

Here's my JavaScript:

function privacy(current)
{
    var $this = $(current), 
    $scope = $this.closest('.uk-button-group'), 
    value = $this.val();
    $.ajax({
        type: 'post',
        url: '/privacy.php',
        data: {key: value },
        success: function () {
        }
    });
}
$(function() {
    $("#privacy1, #privacy2, #privacy3").click(function() {
        privacy($this);
        alert('A button has been clicked!');
    });
});

And here's my HTML:

<div class="uk-button-group">
    <button class="uk-button" id="privacy1" value="1">Public</button>
    <button class="uk-button" id="privacy2" value="2">Protected</button>
    <button class="uk-button" id="privacy3" value="3">Private</button>
</div>    

When I click on one of the buttons, it should call the privacy function and alert me that a button has been clicked but it doesn't. Can anyone help me and show me what's wrong with my code? Much appreciated thank you!

You do not have any identifier $this , you probably need to change $this with $(this) or simply this to pass the event source object

privacy(this);

OR

privacy($(this));

替换为:

privacy(this);

Try here: http://jsfiddle.net/pqdgT/

$(function() {
    $("#privacy1, #privacy2, #privacy3").click(function() {
        privacy($(this));
        alert('A button has been clicked!');
    });
});

Here is your working code

And here is the refined code

function privacy(current)
{
    var btn = $(current), 
    scope = $(btn).closest('.uk-button-group'), 
    value = $(btn).val();
    $.ajax({
        type: 'post',
        url: '/privacy.php',
        data: {key: value },
        success: function () {
        }
    });
}
$(function() {
    $("#privacy1, #privacy2, #privacy3").click(function() {
        privacy(this);
        alert('A button has been clicked!');
    });
});

Please avoid reserved keywords while naming variables - Here is the list of reserved words

And be careful with your syntax and feel free to use the browser console.

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