单击jquery调用函数

时间:2012-07-07 05:08:39

标签: jquery

我在点击时调用函数时遇到问题。以下是我的代码:

JavaScript的:

$(document).ready(function(){       
    function showMessage(msg) {
        alert(msg);
    };      
})

HTML:

<input type="button" value="ahaha"  onclick="$(this).showMessage('msg');" />

由于某些原因我无法使用click()功能。请帮帮我。

4 个答案:

答案 0 :(得分:4)

一些事情:

  • showMessage()不是jQuery对象的属性。这只是一个常规功能。
  • 如果您使用的是jQuery,请不要使用onclick。使用JavaScript绑定所有事件。

有几种方法可以修复此代码。这是一个:

<强>的JavaScript

$.fn.showMessage = function(message) {
  alert(message);
};

$(document).ready(function() {  
  $('#button').on('click', function() {
    $(this).showMessage('I am a message');
  });
});

<强> HTML

<input type="button" value="ahaha" id="button" />

答案 1 :(得分:1)

没有$(this)请..只需这样打电话:onclick="showmessage('msg')"

答案 2 :(得分:1)

$(document).ready(function(){      
        function showMessage(msg) {
       alert(msg);
    };      <-----  i think this semicolon is not needed
        })  <-----  Should provide semicolon here as its the main function ending

答案 3 :(得分:0)

有几种方法可以做到这一点。

让我对你的HTML进行一些修改,

<input id="myTest" value="CLICK ME!!!" title="HELLO WORLD!!!" type="button" />

接下来让我们看看如何使用jQuery

执行此操作
$(document).ready(function() {
  $('input#myTest').click(function() {
    var el = $(this),
        msg = el.attr('title');
    alert(msg);
  });
});

希望这有帮助, 干杯

相关问题