简体   繁体   中英

Register On-Click Event with jQuery - Not Firing

Should be a quickie ...

1) I created a new project in VS2013 using MVC.
2) I added the following code to the bottom of the default Home\\Index.cshtml that is created with the project template.

<button class="myalertclass">Alert me</button>

<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")">
    $(document).on('click', '.myalertclass', function (e) {
        alert('Hello you');
    })
</script>

I was now expecting that when I click the "Alert me" button, I'll get a message box with "Hello you", but no such joy.

The problem is that when I click the button, the event is not fired. I guess I'm missing some wiring somewhere, but am stumped.

According to w3.org (emphasis mine):

The script may be defined within the contents of the SCRIPT element or in an external file. If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

That's to say, you can't specify both a src and a body for your script element and expect both to work... so, use two separate script elements.

<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
<script>
    $(document).on('click', '.myalertclass', function (e) {
        alert('Hello you');
    })
</script>

You can not include inline scripts in a referenced script tag. Try this:

<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>

<script>
    $(document).on('click', '.myalertclass', function (e) {
        alert('Hello you');
    })
</script>

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