简体   繁体   English

jQuery:从用户控件捕获单击事件

[英]jQuery: catch click event from usercontrol

I've got UserControl with button. 我有带按钮的UserControl。 I'm trying to catch click event of this button using jQuery. 我正在尝试使用jQuery捕获此按钮的点击事件。 My code in ascx: 我在ascx中的代码:

<link type="text/css" href="css/jquery-ui-1.8.22.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.22.custom.min.js"></script>
<script type="text/javascript" src="js/myjQueryCode.js"></script>

<button id="test-button">Test</button>

Code in myjQueryCode.js. myjQueryCode.js中的代码。

I've tried this: 我已经试过了:

$('#test-button').bind('click', function() {
    alert("123");
});

and this: 和这个:

$("[id$=test-button]")
    .button()
    .click(function() {
        alert("123");
});

and this: 和这个:

$('#test-button')
    .button()
    .click(function() {
        alert("123");
});

Nothing is work. 没事。

Have you tried to put your code iside the $(document).ready() ? 您是否尝试过将代码放在$(document).ready()旁边? Try this: 尝试这个:

$(document).ready(function(){

    $('#test-button').bind('click', function() {
        alert("123");
    });

});

It should just be: 应该只是:

$('#test-button').click(function () {
    console.log('Click activated.');
});

Make sure that the code can actually execute. 确保代码可以实际执行。 For example, wrap the statement in an executed function like so: 例如,将语句包装在一个已执行的函数中,如下所示:

(function () {
    // Write code here
}());

Or execute once the document is ready, like so: 或在文档准备好后执行,如下所示:

$(document).ready(function () {
    // Write code here
});

尝试将脚本代码放在html代码之后-也许这会有所帮助...

Your jQuery code is being executed before the element exists (because the <script> tag is before the HTML for your button), so you'll need to wrap it in a DOM ready event handler. 您的jQuery代码是在元素存在之前执行的(因为<script>标记位于按钮的HTML之前),因此您需要将其包装在DOM ready事件处理程序中。 Like so: 像这样:

$(document).ready(function() {
    $('#test-button').bind('click', function() {
        alert("123");
    });
});

For further information, look at the API documentation for the .ready() function and the Getting Started with jQuery tutorial. 有关更多信息,请参阅.ready()函数的API文档和jQuery入门教程。

Your first approach using jQuery, and not referencing .button() works in jsfiddle: http://jsfiddle.net/Cd5Qj/ 您使用jQuery而不引用.button()的第一种方法在jsfiddle中有效: http : //jsfiddle.net/Cd5Qj/

So it's likely that either you've got the wrong path to the jQuery library in your script tag, or you're not including the code inside a jQuery block like: 因此,很可能是您在script标签中的jQuery库路径错误,或者您没有在jQuery块中包含代码,例如:

$(function(){
  ... //code here
});

...or there's some conflict we can't examine because there's more code you haven't displayed here. ...或者存在一些我们无法检查的冲突,因为这里没有显示更多代码。

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

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