Reputation: 1520
I have a View
and Desk.js
file with javascript code.
In the View
:
<script src='@Url.Content("~/Scripts/KazBilet/Desk.js")' type="text/javascript"></script>
In the Desk.js
file:
$(function () {
$('.wraper').load('/desk/getsessionscreen');
toggleSession();
});
function toggleSession() {
alert('a');
$('.sched a').on('click', function () {
var target = $(this);
$(this).toggleClass('selected');
$('.sched a').not(target).each(function () {
$(this).removeClass('selected');
});
setStateForStepButton();
});
}
The elements with sched
class and a
tags contains in partial view which loaded in wraper
div element.
The problem in that click
handler not fire, but alert
calls fine. How to solve it?
Thanks
Upvotes: 0
Views: 2660
Reputation: 620
The code seems to be correct, but I had some problems in the past with on()
. Try this:
$(document).on('click', '.sched a', function () {
var target = $(this);
$(this).toggleClass('selected');
$('.sched a').not(target).each(function () {
$(this).removeClass('selected');
});
setStateForStepButton();
});
Also, if you are trying to set the class selected
only to the a
clicked, I should rewrite your code as:
$(document).on('click', '.sched a', function () {
$('.sched a').removeClass('selected');
$(this).addClass('selected');
setStateForStepButton();
});
And as yan.kun said, call the function on the callback of load()
Upvotes: 0
Reputation: 6908
You need to call toggleSession() in the callback of load, otherwise the content might not have been loaded yet, so your selector can't find the desired element.
$('.wraper').load('/desk/getsessionscreen', function () {
toggleSession();
});
Upvotes: 1
Reputation: 1038710
You could put your click subscription code outside. You don't even need to wait for the DOM to be ready:
$('.sched').on('click', 'a', function () {
var target = $(this);
$(this).toggleClass('selected');
$('.sched a').not(target).each(function () {
$(this).removeClass('selected');
});
setStateForStepButton();
});
$(function () {
$('.wraper').load('/desk/getsessionscreen', function() {
toggleSession();
});
});
function toggleSession() {
alert('a');
}
Also notice the correct overload I am using for the .on()
method if you want to register lively:
$('.sched').on('click', 'a', function () {
Also note that if you want to call the toggleSession
function when the AJAX call succeeds you should use the success callback of the .load
method.
Upvotes: 2