0

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

JavaScript:

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

HTML:

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

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

4

4 回答 4

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" />
于 2012-07-07T05:14:25.543 回答
1

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

于 2012-07-07T05:13:41.507 回答
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
于 2012-07-07T05:15:18.967 回答
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);
  });
});

希望这会有所帮助,干杯

于 2012-07-07T05:22:46.027 回答