2

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.

Travis J
  • 81,153
  • 41
  • 202
  • 273
Neil W
  • 7,670
  • 3
  • 28
  • 41
  • 2
    You can't specify a `src` _and_ a body for your script element... so, use two. – canon Oct 30 '13 at 17:17
  • possible duplicate of [What if script tag has both "src" and inline script?](http://stackoverflow.com/questions/3540581/what-if-script-tag-has-both-src-and-inline-script) – zzzzBov Jan 31 '14 at 19:19

2 Answers2

3

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>
canon
  • 40,609
  • 10
  • 73
  • 97
0

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>
amiry jd
  • 27,021
  • 30
  • 116
  • 215