简体   繁体   中英

The function does not pass parameters to onclick

Reactor code and I came across a small problem. I've read the value of variables from a prompt that runs on an onclick of a given element. Now I am trying to write a global function, containing all possible parameters and after typing, depending on where the function was called creates an element in the right place on the page and adds the entered parameters. I applied here the switch, passed the parameters, although the element is not added to the additional box, for example, why?

 var overlay = $("#overlay"); var message = $("#message"); function popupshow() { overlay.css("display", "block"); } function popuphide() { overlay.css("display", "none"); } function params(type) { param1 = $("#param1").val(); param2 = $("#param2").val(); param3 = $("#param3").val(); param4 = $("#param4").val(); param5 = $("#param5").val(); param6 = $("#param6").val(); switch (type) { case img: $("#additional-box").append('<img src="' + param6 + '" style="width: ' + param2 + 'px; height: ' + param3 + 'px;">'); break; case otherimg: $("#other-photos").append('<img src="' + param6 + '" style="width: ' + param2 + 'px; height: ' + param3 + 'px;">'); break; case section: $("#new_section").append('<div class="sekcja" style="width: ' + param2 + 'px; height: ' + param3 + 'px; background: #' + param4 + '; color: #' + param5 + ';"></div>'); break; case gallery: $("#gallery").append('<img src="' + param6 + '" />'); break; } } $("#add-params").on("click", function() { params(img); }); $("#additional-img").on("click", function() { popupshow(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="overlay"> <div id="message"> <p id="m-title">Params</p> <input type="text" placeholder="Section title" name="param1" id="param1" /> <input type="text" placeholder="Element width" name="param2" id="param2" /> <input type="text" placeholder="Element height" name="param3" id="param3" /> <input type="text" placeholder="Element background" name="param4" id="param4" /> <input type="text" placeholder="Element color" name="param5" id="param5" /> <input type="text" placeholder="Source" name="param6" id="param6" /> <button type="button" id="add-params">Add to template</button> </div> </div> <div id="additional-box"> </div> <div id="additional-img"> <button type="button">Add image</button> <span>Image adding is optional.</span> </div> 

Your parameter should be a string.

$("#add-params").on("click", function() {
  params("img");
});

And in your switch case, you are suppose to compare your parameter with a string only as like below.

switch (type) {      
    case "img":

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM