2015-08-29 2 views
0

Я хотел бы знать, как я могу определить большую переменную для набора переменных, которые я имею в : showFootnotesPanel();, showReferencesPanel();, showImagesPanel();, showInformationPanel();.Как определить переменную нескольких переменных в JavaScript

Будет ли это примерно так?

function showPanel() { 
    var x = [showFootnotesPanel();showReferencesPanel();showImagesPanel();showInformationPanel();] 
} 

Update:

У меня есть эта функция, которая используется, чтобы открыть боковую панель с правой стороны и цвет содержание:

var els = document.getElementsByClassName('change-color'), 
    target = document.getElementsByClassName('resources'), 
    changeColor = function(a) { 
    elements = document.getElementsByClassName("note"); 

    for (var i = 0; i < elements.length; i++) { 
     console.log(elements[i]) 
     elements[i].style.backgroundColor = ""; 
    } 
    target = a.getAttribute('href'); 
    element = document.querySelector('[data-id="' + target.substring(1, target.length) + '"]'); 
    element.style.backgroundColor = a.getAttribute('data-color'); 

    }; 
for (var i = els.length - 1; i >= 0; --i) { 
    els[i].onclick = function() { 
    showFootnotesPanel(); 
    changeColor(this); 
    } 

Теперь у меня есть 4 боковые панели, которые должны отвечать к тому же сценарию, и я подумал, что, определив что-то вроде showPanel(), showFootnotesPanel() или showReferencesPanel() или showImagesPanel() или showInformationPanel() Я мог бы упростить вещи, поэтому последняя строка скрипта быть это вместо того, чтобы просто:

els[i].onclick = function(){showPanel();changeColor(this);} 

Update 2:

Или это можно сделать с помощью логического оператора OR?

els[i].onclick = function(){showFootnotesPanel(); || showReferencesPanel(); || showImagesPanel(); || showInformationPanel();changeColor(this);} 

Update 3:

Это новый сценарий, который я использую, чтобы скрыть и показать панели:

function showPanel(myPanel) { 
    var elem = document.getElementById(myPanel); 
    if (elem.classList) { 
    console.log("classList supported"); 
    elem.classList.toggle("show"); 
    } else { 
    var classes = elem.className; 
    if (classes.indexOf("show") >= 0) { 
     elem.className = classes.replace("show", ""); 
    } else { 
     elem.className = classes + " show"; 
    } 
    console.log(elem.className); 
    } 
} 


function hideOthers(one, two, three, four) { 
    if (one > "") { 
    var elem1 = document.getElementById(one); 
    var classes = elem1.className; 
    elem1.className = classes.replace("show", ""); 
    } 
    if (two > "") { 
    var elem2 = document.getElementById(two); 
    var classes = elem2.className; 
    elem2.className = classes.replace("show", ""); 
    } 
    if (three > "") { 
    var elem3 = document.getElementById(three); 
    var classes = elem3.className; 
    elem3.className = classes.replace("show", ""); 
    } 
    if (four > "") { 
    var elem4 = document.getElementById(four); 
    var classes = elem4.className; 
    elem4.className = classes.replace("show", ""); 
    } 
    return; 
} 

И это скрипт, который вызывает панель и выделяет текст на них:

var els = document.getElementsByClassName('change-color'), 
    target = document.getElementsByClassName('resources'), 
    changeColor = function(a) { 
    elements = document.getElementsByClassName("note"); 

    for (var i = 0; i < elements.length; i++) { 
     console.log(elements[i]) 
     elements[i].style.backgroundColor = ""; 
    } 
    target = a.getAttribute('href'); 
    element = document.querySelector('[data-id="' + target.substring(1, target.length) + '"]'); 
    element.style.backgroundColor = a.getAttribute('data-color'); 

    }; 
for (var i = els.length - 1; i >= 0; --i) { 
    els[i].onclick = function() { 
    hideOthers('footnotes-section', 'references-section', 'images-section', 'information-section'); 
    showPanel('references-section'); 
    changeColor(this); 
    } 
} 

Спасибо!

+1

что вы пытаетесь сделать, есть несколько способов сделать это. Если вы скажете, что вам нужно, у вас будет лучший ответ. –

+0

У меня есть ощущение, что вы просто хотите упростить код и иметь одну функцию вместо 4,5 различных функций? – sinisake

+0

Я знал ... Передайте разные аргументы функции showPanel() и на основе аргументов - запустите код. Если 5 функций выполняют одно и то же действие с 5 различными элементами на странице - да, вы правы, это может/должна быть одной функцией. – sinisake

ответ

0

Я точно не понимаю ваш вопрос, но если вы хотите определить переменную, содержащую другие переменные, вы можете использовать объект.

например:

var footNotesPanel = true; 
var referencesPanel = true; 
var imagesPanel = true; 

var showPanels = { 
    footNotesPanel: footNotesPanel, 
    referencesPanel: referencesPanel, 
    imagesPanel: imagesPanel 
} 

/* 
    Option 2 - for showing/hiding side panels 
    1) create all your panels as they would appear, with all the data, but hide them with display:none; 
    2) call show panel function to show a panel. 
*/ 

var showPanel(panel_id) { 
    var panel_element = $("#" + panel_id); /*panel that you want to show (is hidden atm but somewhere on the page */ 
    if (!panel_element.length) { 
    return false; //no panel with this id currently on page 
    } else { 
    //check the panel id and do some custom editing if needed, eg. 
    if (panel_id == "main_side_panel") { 
     //add some additional classes to body element etc 
    } 
    panel_element.show(); 

    //Or Another option that you probably are looking for is below 
    if (panel_id == "footnotes_panel") { 
     showFootnotesPanel(); 
    } else if (panel_id == "images_panel") { 
     showImagesPanel(); 
    } 
    } 
} 

// And use it like this: 
<div id="footnotes_panel" onclick="showPanel('footnotes_panel')"></div> 
// Or simply get the element id from `event.target` and use `showPanel()` without arguments. 
+0

Я хочу, чтобы на боковой панели была открыта соответствующая информация, то есть функция могла сказать: откройте эту панель или эту панель, или эту панель или эту панель, в зависимости от триггера, который я размещаю на веб-сайте. – AnaPM

+0

Почему вы просто не создали общую функцию showPanel, которая принимает идентификатор панели, которую вы хотите показать, а затем ... делает ее видимой? –

1

Обновленный с окончательным решением.

В JavaScript можно объявить переменные следующим образом:

var text = ""; // String variable. 
var number = 0; //Numeric variable. 
var boolValue = true; //Boolean variable. 
var arrayValue = []; // Array variable. This array can contain objects {}. 
var obj = {}; // Object variable. 

Проверить эту версию кода.

// var text = "";   => String variable. 
 
// var number = 0;   => Numeric variable. 
 
// var boolValue = true;  => Boolean variable. 
 
// var arrayValue = [];  => Array variable. This array can contain objects {}. 
 
// var obj = {};    => Object variable. 
 

 
// This section of code is only to explain the first question. 
 
(function() { 
 
    function showFootnotesPanel() { 
 
    return 10; // Random value. 
 
    } 
 

 
    function showReferencesPanel() { 
 
    return 30; // Random value. 
 
    } 
 

 
    function showImagesPanel() { 
 
    return 50; // Random value. 
 
    } 
 

 
    function showInformationPanel() { 
 
    return 90; // Random value. 
 
    } 
 

 
    function showPanel() { 
 
    return [ 
 
     showFootnotesPanel(), // Index = 0 
 
     showReferencesPanel(), // Index = 1 
 
     showImagesPanel(), // Index = 2 
 
     showInformationPanel() // Index = 3 
 
    ]; 
 
    } 
 

 
    var bigVariable = showPanel(); // bigVariable is array of numeric values. 
 

 
    // Using logical operator to check status of variable about this demo code. 
 
    if (bigVariable[0] === 10 || bigVariable[1] === 30) { 
 
    console.log("Hey, with these values can show the FootnotesPanel and ReferencesPanel."); 
 
    } else { 
 
    console.log("With the current values can't show anything..."); 
 
    } 
 

 
    console.log(bigVariable); 
 
})(); 
 

 

 

 
// https://jsfiddle.net/dannyjhonston/t5e8g22b/ 
 
// This section of code attempts to answer the question of this post. 
 
(function() { 
 
    // This function can be executed when the page is loaded. 
 
    function showPanel(panels) { 
 
    var panel, panelVisible = ""; 
 
    var selPanels = document.getElementById("selPanels"); 
 

 
    // In panels array... 
 
    for (var i = 0; i < panels.length; i++) { 
 
     // panels[0] = "ReferencesPanel"; 
 
     panel = document.getElementById(panels[i]); // Get in the DOM tag context of the panel to set in the variable "panel". 
 
     panelVisible = panel.getAttribute("data-visible"); // HTML5 data attribute. 
 
     if (panelVisible == "true") { 
 
     panel.setAttribute("class", "show"); 
 
     } else { 
 
     panel.setAttribute("class", "hide"); 
 
     } 
 
    } 
 
    } 
 

 
    // This function is for set panel visibilty. 
 
    function setPanel(panelId, status) { 
 
    panel = document.getElementById(panelId); 
 
    panel.setAttribute("data-visible", status); 
 

 
    // Calling the showPanel function to check in the DOM. 
 
    showPanel(["ReferencesPanel", "InformationPanel", "ImagesPanel", "FootnotesPanel"]); 
 
    } 
 

 
    // Binding the change event to the select tag. 
 
    selPanels.addEventListener("change", function() { 
 
    // Executes setPanel function with panelId and true to update the data-visible attribute in the DOM. 
 
    setPanel(this.options[this.selectedIndex].value, "true"); 
 
    }); 
 

 

 
    // Executes showPanel function with array argument with panels Id. You need to specify every panel that want to handle. 
 
    showPanel(["ReferencesPanel", "InformationPanel", "ImagesPanel", "FootnotesPanel"]); 
 
})();
#global { 
 
    border: solid 1px #6291AD; 
 
} 
 
.tools { 
 
    background-image: linear-gradient(#FFFFFF, #8999CE); 
 
} 
 
#global div[data-visible] { 
 
    height: 80px; 
 
    padding: 5px 0; 
 
} 
 
#global div p { 
 
    padding: 10px; 
 
} 
 
#ReferencesPanel { 
 
    background-image: linear-gradient(#FFFFFF, #FD9A9A); 
 
    float: left; 
 
    width: 20%; 
 
} 
 
#InformationPanel { 
 
    background-image: linear-gradient(#FFFFFF, #A1C7F1); 
 
    float: left; 
 
    width: 80%; 
 
} 
 
#ImagesPanel { 
 
    background-image: linear-gradient(#C6E9FB, #FFF); 
 
    width: 100%; 
 
} 
 
#FootnotesPanel { 
 
    background-image: linear-gradient(#C6E999, #FFF); 
 
    width: 100%; 
 
} 
 
.clear { 
 
    clear: both; 
 
} 
 
.show { 
 
    display: block; 
 
} 
 
.hide { 
 
    display: none; 
 
}
<div id="global"> 
 
    <div class="tools">Show Panel: 
 
    <br /> 
 
    <!-- Demo --> 
 
    <select id="selPanels"> 
 
     <option value="">[SELECT]</option> 
 
     <option value="ReferencesPanel">ReferencesPanel</option> 
 
     <option value="InformationPanel">InformationPanel</option> 
 
     <option value="ImagesPanel">ImagesPanel</option> 
 
     <option value="FootnotesPanel">FootnotesPanel</option> 
 
    </select> 
 
    </div> 
 
    <!-- You need to set data-visible attribute with true or false to show or hide a panel. --> 
 
    <div id="ReferencesPanel" data-visible="false"> 
 
    <p>References Panel</p> 
 
    </div> 
 
    <div id="InformationPanel" data-visible="false"> 
 
    <p>Information Panel</p> 
 
    </div> 
 
    <div class="clear"></div> 
 
    <div id="ImagesPanel" data-visible="false"> 
 
    <p>Images Panel</p> 
 
    </div> 
 
    <div id="FootnotesPanel" data-visible="false"> 
 
    <p>Foot notes Panel</p> 
 
    </div> 
 
</div>

+0

Я знаю, что вы сказали «случайное значение» для возврата каждой функции, но на чем основаны эти значения? – AnaPM

+0

Например, вы можете объявить переменную как результат функции. Этот код был разработан только для того, чтобы показать вам, как объявить переменную с предыдущими значениями каждой функции, которая независимо возвращает значение. Речь идет о вашем первом вопросе. Функция showPanel() {var x = showFootnotesPanel(); showReferencesPanel(); showImagesPanel(); showInformationPanel();]} Кстати, я недавно проверил ваш последний код. –

+0

Ваш последний код неверен. els [i] .onclick = function() {showFootnotesPanel(); || showReferencesPanel(); || showImagesPanel(); || showInformationPanel(); changeColor (this);} The || оператор - оператор сравнения, который используется в логических операторах для определения равенства или разности между переменными или значениями. Вы должны попробовать это: если (showFootnotesPanel() == "anyValue" || showReferencesPanel() == "otherValye") Я отправил и обновление о моем демо-коде. –

Смежные вопросы