一个文本字段中的值没有返回任何内容

3
我正在尝试构建一个小应用程序,用户输入商店名称,该名称将成为图像的alt文本和他们商店的URL,该URL将成为h ref,然后生成一些复制并粘贴代码以在其网站上使用。
我的问题是,当尝试使用原始JavaScript读取商店名称的值时,没有显示任何内容。
请参见我的fiddle: http://jsfiddle.net/willwebdesigner/gVCcm/
$(document).ready(function() { 

    //  Creates a method and prototype for the Array for splicing up words
    Array.prototype.removeByValue = function(val) {
        for(var i=0; i<this.length; i++) {
            if(this[i] == val) {
                this.splice(i, 1);
                break;
            }
        }
    }

    var myStore = {
        storeName: document.getElementById("storeName").value,
        Url: document.getElementById("yourURL"),
        instructions: "<p>Please copy the code above and paste it into your webpage to display the shop4support logo and a link to your store.</p>",

        blackLogo: function() {
            return "&lt;img src=&quot;https://www.shop4support.com/Resources/home/information/InformationForProviders/Availables4s-bk.jpg&quot; alt=&quot;" + this.storeName + " is available on shop4support&quot; /&gt;";
        }
    }

    $("#urlForm").submit(function(e) {

        // Clear output form first
        $(output).html(' ');
        e.preventDefault();

        // Create an array for conditional statements
        var address = [];
        address = $(myStore.Url).val().split("www");

        // Need to put a conditional in here to detect if https://
        if(address[0] === "https://") {
            $(output)
                .slideDown()
                .prepend("&lt;a href=&quot;"+ $(myStore.Url).val() + "&quot;&gt;" + myStore.blackLogo() + "&lt;/a&gt; ")
                .append(myStore.instructions);

        } else if(address[0] === "http://") {
            // Remove the http part off the URL
            var removeHttp = address;
            removeHttp.removeByValue('http://');
            $(output)
                .slideDown()
                .prepend("&lt;a href=&quot;https://www" + removeHttp + "&quot;&gt;" + myStore.blackLogo() + "&lt;/a&gt; ")
                .append(myStore.instructions);

        } else {
            $(output)
                .slideDown()
                .prepend("&lt;a href=&quot;https://"+ $(myStore.Url).val() + "&quot;&gt;" + myStore.blackLogo() + "&lt;/a&gt; ")
                .append(myStore.instructions);
        }
    });
});

感谢 Will

3个回答

3
在初始化myStore对象的时候,值还没有填充。您需要在提交时完成此操作。
因此,您可以将var myStore = {}移动到提交回调函数中:

http://jsfiddle.net/gVCcm/1/


1
更新您的代码如下:
    $("#urlForm").submit(function(e) {
               myStore.storeName= (document.getElementById("storeName").value);
   /* The rest of your code */
    }

谢谢,这对我有帮助并且很合理。你能告诉我为什么要把document.getElementById括起来吗?我去掉了括号,它也能完美运行。 - William Li
什么也没有,我只是打印了一些值并将其更改了,忘记改括号了! - internals-in

0

在以下位置初始化您的myStore变量:

$("#urlForm").submit(function(e) {
 var myStore = {}
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接