In the following code, what does the empty jQuery selector $() mean? Does it mean $(document)?
var menu = {
setting:{
isSimpleData:true,
treeNodeKey:"mid",
treeNodeParentKey:"pid",
showLine:true,
root:{
isRoot:true,
nodes:[]
}
} ,
loadMenuTree:function(){
$("#menuTree").zTree(menu.setting, privilegeDate);
}
};
$().ready(function(){
menu.loadMenuTree();
});
does it mean $(document)?
No, it means an empty jQuery collection, but $.fn.ready doesn’t actually care what’s in the jQuery collection:
> $().length
0
> $.fn.ready
function (a){return n.ready.promise().done(a),this}
Note how it doesn’t make use of this except to return it for chaining. You could use $(document).ready, $().ready, $('body').ready, $('blink').ready… but the only non-deprecated way is by passing the listener to the jQuery function itself:
$(function () {
menu.loadMenuTree();
});
Related
If I just have this js everything fires and works:
$('.hidden-div').hide();
$('#id_bool').change(function() {
$('.hidden-div').toggle(this.true);
});
but if I add this function directly underneath it everything stops working:
$('.form').on('submit', function(){
if $('#id_bool'){
$('.hidden-div').show();
} else {
$('.hidden-div').hide();
}
});
What is going wrong in the second part?
You forget to add parentheses in your if statement:
$('.form').on('submit', function(){
if ($('#id_bool')){
$('.hidden-div').show();
} else {
$('.hidden-div').hide();
}
});
In JQuery a selector will always return a JQuery array, you need to specify a property to check.
This:
if ($('#id_bool')){
should be:
if ($('#id_bool:checked').length){
Edit:
if your id_bool has a value, that can be either true or false you can, as #Bargi mentions, use this:
if ($('#id_bool').val()){
I am currently adding flagging functionality to a project of mine, and I can't get jQuery's $(this) selector to work.
The goal of this is to change the text in the div from flag to flagged when the user clicks it, and the ajax query runs successfully. My HTML/PHP is:
<div class="flag" post_to_flag='".$post_to_flag."'>Flag</div>
And my javascript that deals with the div is:
$('.flag').live('click', function () {
$.post('../php/core.inc.php', {
action: 'flag',
post_to_flag: $(this).attr('post_to_flag')
}, function (flag_return) {
if (flag_return == 'query_success') {
$(this).text('flagged');
} else {
alert(flag_return);
}
});
});
I can't replace the text with flagged, but if I replace the this selector with the .flag selector, it will replace everything with the class of flag on the page.
I have checked, and the $(this) selector is getting the attribute of 'post_to_flag' just fine. Why is this happening, and how can I fix it?
You should add a context variable:
$('.flag').live('click', function () {
var $context = $(this);
$.post('../php/core.inc.php', {
action: 'flag',
post_to_flag: $context.attr('post_to_flag')
}, function (flag_return) {
if (flag_return == 'query_success') {
$context.text('flagged');
} else {
alert(flag_return);
}
});
});
You are calling multiple functions within your jQuery selection call. When you go into that $.post() function, your scope changes. this now refers to a different scope from when you were inside one().
#Moak's suggestion, if you set a variable to a jQuery object, it's probably best to denote the variable with a beginning $ just for potential clarity for future readers or yourself.
this inside the ajax callback is not the element, but it is the Ajax object itself.
You can use $.proxy to pass in the context.
Ref $.proxy
$('.flag').live('click', function () {
$.post('../php/core.inc.php',
{action: 'flag', post_to_flag: $(this).attr('post_to_flag')},
$.proxy(function(flag_return) {
if(flag_return == 'query_success'){
$(this).text('flagged'); //Now this here will represent .flag
}else{
alert(flag_return);
}
},this)); //Now here you are passing in the context of `.flag`
I have this situation.
$(document).ready(function(){
$.each(elements,do());
});
I would like to execute another new method after the $.each() has finished new method called doOther().
Where I can set my new method for example doOther(); ? I have new $.each inside new method just for info.
Update
This is my script
$(function(){
$.each($('.countdown'), function() {
var _element = '.countdown-'+$(this).attr("id");
if ($(_element).length > 0) {
var _expDate = $(_element).attr('data-expiration').split(',');
_expDate.forEach(function(v,i,a){a[i]=parseInt(a[i]);});
var _datetime = new Date(_expDate[0],_expDate[1],_expDate[2],_expDate[3],_expDate[4],_expDate[5]);
init_countdown(_element,_datetime);
}
});
$.each($('.countdown'),function() {
var ips = $(this).text().split(',');
$(this).html('<div class="span12">'+ips[0]+'</div>');
});
});
function init_countdown(_element,_datetime){
$(_element).countdown({
date: _datetime /*"June 7, 2087 15:03:26"*/
});
}
it seems that $.each($('.countdown') etc.. is overridden by the first $.each, can't understand why.
If I've understood what you mean, your code should look like this:
$(document).ready(function(){
$.each(elements, do);
doOther();
});
If this isn't what you meant, please edit your original question and add more detail.
This should do it,
$(document).ready( function(){
$.each(elements,do());
doOther();
} );
Implement another method right after your first $.each block
I'm trying to run a function twice. Once when the page loads, and then again on click. Not sure what I'm doing wrong. Here is my code:
$('div').each(function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').truncate();
$(this).show();
}
});
The problem is on line 13 where I call the truncate(); function a second time. Any idea why it's not working?
Edit jsFiddle here: http://jsfiddle.net/g6PLu/
That's a named function literal.
The name is only visible within the scope of the function.
Therefore, truncate doesn't exist outside of the handler.
Instead, create a normal function and pass it to each():
function truncate() { ...}
$('div').each(truncate);
What's the error message do you get?
You should create function and then call it as per requirement
Define the function
function truncate(){
$('div').each(function(){
});
}
Then call the function
truncate();
Another approach is to establish, then trigger, a custom event :
$('div').on('truncate', function() {
$(this).......;
}).trigger('truncate');
Then, wherever else you need the same action, trigger the event again.
To truncate all divs :
$('div').trigger('truncate');
Similarly you can truncate just one particular div :
$('div#myDiv').trigger('truncate');
The only prerequisite is that the custom event handler has been attached, so ...
$('p').trigger('truncate');
would do nothing because a truncate handler has not been established for p elements.
I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate). And makes for much cleaner code
(function($) {
$.fn.truncate = function() {
this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
};
$.fn.untruncate = function() {
this.removeClass('closed').children().show();
};
})(jQuery);
$('div').truncate();
$('.truncate').click(function() {
var $parent = $(this).parent();
if ($parent.hasClass('closed')) {
$parent.untruncate();
} else {
$parent.truncate();
}
});
I'd like to check ancestry using two jQuery objects. They don't have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called get()). jQuery's is() only works with expressions, so this code would be ideal but will not work:
var someDiv = $('#div');
$('a').click(function() {
if ($(this).parents().is(someDiv)) {
alert('boo');
}
}
Just want to see if one element is a child of another and I'd like to avoid stepping back into DOM land if possible.
You can use the index() method to check if an element exists in a list, so would the following work?
var someDiv = $('#div');
$('a').click(function() {
if ($(this).parents().index(someDiv) >= 0) {
alert('boo');
}
}
From #index reference.
Checking for (this).parents().index(someDiv) >= 0, as #Gareth suggests, will work just fine.
However, using the jQuery ancestry plugin is way faster / more efficient.
Along those lines, parents() optionally accepts a selector itself:
$('a').click(function() {
if ($(this).parents("#div").length) {
alert('boo');
}
});
One way would be to use the filter function
$('a').click(function() {
$(this).parents().filter(function() {
return this == someDiv[0];
}).each(function() {
alert('foo');
})
}
I think you may also be able to get away with using jQuery.inArray
if ($.inArray( someDiv, $(this).parents() ) ) {
alert('boo');
}
Would you not get the result you want from simply using a CSS selector?
$( '#div a' ).click( function() { ... } );
Try this:
var someDiv = $('#div');
$('a').click(function() {
if ($.inArray($(this).parents().get(), someDiv.get(0)) {
alert('boo');
}
}
var $element = $('a');
while ($element && !$element.is('someDiv')) {
var $element = $element.parent();
};