从表单中派生要使用javascript对象加载的图像路径

derive image path to load using javascript objects from a form

本文关键字:加载 对象 图像 路径 javascript 表单 派生      更新时间:2023-10-21

我现在正在尝试学习一些javascript,并想练习一些表单操作,做我自己很棒的pizzaconfigurator(有点像papa joes上的那个)-希望你能指导我一点过程

html(分解为重要部分):

<input type="radio" name="crust" value="crust"  class="userChoice" onclick="parameter1(this.value)" checked>Pizza with normal crust.</input>
<input type="radio" name="crust" value="cheesycrust"  class="userChoice" onclick="parameter1(this.value)">Pizza with cheese in the crust.</input>
<h2>Pizza Topping:</h2>
<input type="radio" name="pizzaType" value="margarita" onclick="parameter2(this.value)">tomato sauce and cheese
<input type="radio" name="pizzaType" value="funghi" onclick="parameter2(this.value)">tomato sauce, cheese and mushrooms
<input type="radio" name="pizzaType" value="tonno" onclick="parameter2(this.value)">tomato sauce, cheese and tuna
<input type="radio" name="pizzaType" value="alcapone" onclick="parameter2(this.value)">tomato sauce, cheese, bacon, salami and anchovis 
......
<h2>Size:</h2>
    <select id="size" onChange="parameter3(this.value)">
        <option value="1">normal</option>
        <option value="2">family size</option>
     </select>
<span id="checkMyOrder"></span>

javascript:

var pizzaConfigurator = {
path: parameter1 + parameter2 + parameter3 +".jpeg",
parameter1: function (value1) {
    this.parameter1 = value1;
},
parameter2: function (value2) {
    this.parameter2 = value2;
},
parameter3: function (value3) {
    switch(value3) {
        case "1": this.parameter3 = value3;
        break;
        case "2": this.parameter3 = value3;
        break;
        default:
        alert("Please select size.");
        break;
        }
        return true;
    }
};

所以我现在真正陷入困境的是,我如何在一个最终变量中返回我所有选择的值,并将其传递给一个函数,该函数稍后将填充我的checkOrder或动态加载一个"披萨饼皮-*pizzaType*-大小.jpeg"?

我走对了吗?我试着根据收银台的codeacademy javascript教程来大致建模

在jquery中可以更容易地做到这一点吗?

对于刚开始使用Javascript的人来说,您的模型看起来非常不错。

这里的主要问题是:

  • 不能直接调用像parameter2(this.value)这样的函数,因为它在pizzaConfigurator对象中,它需要是pizzaConfigurator.parameter2

  • This指的是它被调用的函数,所以它永远不会从this.parameter3中获取值,在JavaScript中读取Scope和this以获取更多详细信息

以下是我尝试编写的与您的代码风格类似的工作版本:http://jsfiddle.net/W48Xe/5/

这里有一个JQuery演示(http://jsfiddle.net/sJVaw/2/)完成了同样的工作(但对学习不一定有好处)

建议进一步阅读:模块化JavaScript的自执行函数之上的对象文字的情况

希望它能有所帮助!