简体   繁体   English

通过JavaScript / jQuery单击按钮来调用单击函数

[英]Calling a function on click via JavaScript/jQuery on button clicks

Here's my JavaScript: 这是我的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: 这是我的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 您没有任何标识符$this ,您可能需要使用$(this)更改$this或仅通过this来传递事件源对象

privacy(this);

OR 要么

privacy($(this));

替换为:

privacy(this);

Try here: http://jsfiddle.net/pqdgT/ 在这里尝试: 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. 并且请谨慎使用语法,并随时使用浏览器控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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