As the question says, I can't call a nested function!
Here's the JavaScript:
var n;
var i = 0;
$("#men").click(function(){
$("#reshead").slideToggle("300");
});
$("#nxt").click(function() {
pic(i+=n);
});
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$("#header").addClass("scroll");
} else {
$("#header").removeClass("scroll");
}
});
function pic(n) {
if(n=1){
dx1();
} else if (n==2) {
dx2();
} else if (n=3){
dx3();
} else{
n=0;
}
}
function dx1() {
document.getElementById("picb").style.backgroundImage='url("src/black-belt.png")';
}
function dx2() {
document.getElementById("picb").style.cssText+='background-image:url(src/kut.png);background-repeat:no-repeat; width:auto;height:auto;';
}
function dx3() {
document.getElementById("picb").style.cssText+='background-image:url(src/slmb.jpg);background-repeat:no-repeat; width:auto;height:auto;';
}
I tried everything possible. Nothing happens. The code is for a slideshow in which the background image alone changes.
I first tried it in jQuery but it didn't happen. So I tried in plain JavaScript and it still doesn't work.
if(n=1)
and
else if(n=3)
are assingments and not comparison operators...
You are assigning a value to n so it's always entering to the first if. Try using == operator:
function pic(n) {
if(n==1){
dx1();
}
else if(n==2){
dx2();
}
else if(n==3){
dx3();
}
else{
n=0;
}
}
Be aware that even with the syntax fixes, you will still run into a problem trying to add undefined to 0.
pic(i+=n);
where the first time it is called i equals 0 and n equals undefined. Afterwards, i will equal NaN and n will equal 0.
Related
I'm writing a simple card game, but for some reason this code below behaves very strangely...The turn functions is first called using theTurn(0)
players is an array of objects with player name and hand etc.
function theTurn(playerNumber) {
if(play == 1) {
$('#player').text(players[playerNumber].Name);
$('#submit').click(function() {
nextPlayer(playerNumber);
})
}
}
function nextPlayer(playerNumber) {
if(playerNumber == players.length - 1) {
theTurn(0);
} else {
theTurn(playerNumber + 1);
}
}
For some reason I get player 0 then 1 then 1 again and then 0.
I've left out some of the stuff in theTurn...but this is the gist of it and the problem shows up in this simplified version too.
Any help with my faulty logic would be greatly appreciated.
This actually makes a little more sense... just add the click handler once, then set the player number as a data property so the nextPlayer function knows what it is without an argument.
$('#player').data('activePlayer', 0);
$('#submit').click(function() {
nextPlayer();
});
function theTurn(playerNumber) {
if(play == 1) {
$('#player').text(players[playerNumber].Name);
$('#player').data('activePlayer', playerNumber);
}
}
function nextPlayer() {
var playerNumber = $('#player').data('activePlayer');
if(playerNumber == players.length - 1) {
theTurn(0);
} else {
theTurn(playerNumber + 1);
}
}
please help solve the problem.
live example is here: https://jsfiddle.net/oqc5Lw73/
i generate several tank objects:
var Tank = function(id) {
this.id = id;
Tank.tanks.push(this);
}
Tank.tanks = [];
for (var i = 0; i < 3; i++) {
new Tank(i);
}
Tank.tanks.forEach(function(tank, i, arr) {
console.log(tank);
});
console.log('summary tanks: ' + Tank.tanks.length);
after i delete tank with random index:
var tankDel = Math.floor(Math.random() * (3));
Tank.tanks.splice(tankDel, 1);
Tank.count -= 1;
Tank.tanks.forEach(function(tank, i, arr) {
console.log(tank);
});
console.log('summary tanks: ' + Tank.tanks.length);
i try check tanks massive. if tanks massive contain tank with property 'id' = 0 then i need display alert('tank with id 0 is dead').
but console output follow error message:
Uncaught SyntaxError: Illegal break statement
break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller. See similar post here: illegal use of break statement; javascript
Tank.tanks.forEach(function(tank, i, arr) {
if(tank.id == 0) {
tank0Dead = false;
return;
};
});
if(tank0Dead == true) {
alert('tank with id 0 is dead');
};
jsfiddle : https://jsfiddle.net/oqc5Lw73/6/
You can't quit from forEach using break. Just remove break, and it will work.
P.S: honestly, it is better to refactor that code:)
Your only problem is that you can't use the break; statement in a forEach function.
But you can in a for() loop, so here is the equivalent code with a for :
for (var i = 0; i < Tank.tanks.length; i++){
if (Tank.tanks[i].id == 0){
tank0Dead = false;
break;
}
}
https://jsfiddle.net/oqc5Lw73/5/
But I agree with #dimko1 about the idea of refactoring the code
You can not break a forEach callback, simply because it's a function.
Here's updated working jSfiddle
If you really want to break it, you can use exception like code below.
try {
[1,2,3].forEach(function () {
if(conditionMet) {
throw Error("breaking forEach");
}
});
} catch(e) {
}
Otherwise you can use jQuery's each() method. when it's callback returns false it stops.
jQuery.each([1,2,3], function () {
if(conditionMet) {
return false;
}
});
I cant seem to get this function to return true even after ticking the two check boxes I have on the page. I've been working on this for hours now and running out of ideas. Any help would be much appreciated.
if(myfunction() == true){
alert('YAY!');
}
function myfunction(){
if($("input[type=checkbox]").length > 0){
$('.checkbox').each(function(){
if($(this).prop('checked')){
return true;
}
else{
$(this).find(".CheckboxCheck").show();
return false;
}
});
}
else{
return true;
}
}
You are returning true from within the function that you passed to each, not from myfunction. Except in the case that there are no check boxes on your page, and thus the else block executes in myfunction, myfunction is returning undefined.
You can do something like this however:
if(myfunction() == true){
alert('YAY!');
}
function myfunction(){
var returnValue = true;
if($("input[type=checkbox]").length > 0) {
$('.checkbox').each(function(){
if($(this).prop('checked')){
returnValue = true;
return false; // Stops the each loop.
}
else {
$(this).find(".CheckboxCheck").show();
returnValue = false;
return false; // Stops the each loop.
}
});
}
return returnValue;
}
Now, I'm not exactly sure of what you're trying to do, and you will almost certainly need to tweak the code above. I'm just providing it as a way to illustrate how to get a value out of the function passed to each. If you're trying to determine if all of the checkboxes are checked, for example, then you'll want your each function to look something like this:
var returnValue = true;
...
$('.checkbox').each(function() {
if (!$(this).prop('checked')) {
returnValue = false;
return false;
}
});
EDIT: After looking at the second code snippet again, I realized that the each loop is unnecessary. If you want to determine if all check boxes are checked, all you need is this:
if ($('.checkbox:not(:checked)').length == 0) {
// All .checkbox elements are checked.
}
Now, keep in mind that the :not() and :checked selectors can't utilize the native JS functions, so they are slower, but probably not enough to matter. I prefer the conciseness.
Returning from inside the each callback function will not return from the outer function. The function will return undefined as you haven't specified any return value for it, and that is not equal to true.
You can use a variable for the result, that you set from within the loop:
function myfunction(){
var result = true;
$('.checkbox').each(function(){
if(!$(this).prop('checked')){
result = false;
$(this).find(".CheckboxCheck").show();
return false; // exit the loop
}
});
return result;
}
$('#ID').on('click', function() {
if(!CommonUtil.compareDateById('startDt','endDt',false, false, true)) {
return false;
}
var cnt = 0;
if(!CommonUtil.isNullOrEmptyById('startDt')) { cnt++; }
if(cnt == 0) {
CommonUtil.setFocusById('srchWord','<spring:message code="confirm.input" arguments="XXXX"/>');
return false;
So if I click on #ID, following logic occurs.
And my question is what does
var cnt = 0;
if(!CommonUtil.isNullOrEmptyById('startDt')) {
cnt++;
}
mean?
The function of isNullOrEmptyById is following:
isNullOrEmptyById: function(id) {
var value = this.getTrimValueById(id);
return this.isNullOrEmpty(value);
},
But what does
cnt++;
do in here??
This is just an if conditional block:
if(!CommonUtil.isNullOrEmptyById('startDt')) {
cnt++;
}
So if CommonUtil.isNullOrEmptyById('startDt') resolves to false, then the condition resolves to true and the code in the block is executed:
cnt++;
The ++ operator increments the value. So whatever numeric value is in cnt will be incremented by 1.
In the overall context of the code, it seems to be treating cnt as more of a boolean than an integer, though. Unless there's more code outside of this example, this can be simplified by using this condition for the last conditional block instead of using cnt and then checking its value.
It is actually unnecessary. Since the cnt is only incremented once it's value is either 0 or 1. Instead you could just get rid of all that and use isNullOrEmptyById function.
if(!CommonUtil.isNullOrEmptyById('startDt')){
CommonUtil.setFocusById('srchWord','<spring:message code="confirm.input" arguments="XXXX"/>');
return false;
}
Well, i'm writting my own getElementByClassName and this is my problem :
function getElementByClassName(elemento,clase){
var i = 0;
if(elemento.hasChildNodes()){
while(elemento.childNodes[i]){
if(elemento.childNodes[i].nodeType != 3){
if(elemento.childNodes[i].className == clase){
return elemento.childNodes[i]; // <---- This is my problem, change to alert
}
else {
getElementByClassName(elemento.childNodes[i],clase);
}
}
i++
}
}
}
var div = getElementByClassName(document.body,"foo");
alert(div);
It alerts undefined, but if i put ( in function) alert this alerts [objectHTMLDivElement] and undefined, so why this returns undefined if this recognize that's a [objectHTMLDivElement] with alert?
To answer your question, the reason why your implementation is not working is because you're recursively calling your function in the else clause and doing nothing with the return value. That's why your code is finding the object, but it's never getting returned.
This is a slightly reworked version of yours, but there are also other limitations to your approach, one being elements with multiple classes will not be found (i.e. <div class="foo bar"> will not be returned). Unless you're just doing this as a learning exercise, I suggest going with an existing implementation, like the link in Yoni's answer.
function getElementByClassName(elemento, clase)
{
var i = 0;
if (elemento.hasChildNodes())
{
while (elemento.childNodes[i])
{
if (elemento.childNodes[i].nodeType != 3)
{
if (elemento.childNodes[i].className == clase)
return elemento.childNodes[i];
else
{
var result = getElementByClassName(elemento.childNodes[i], clase);
if (result != null)
return result;
}
}
i++;
}
}
return null;
}