【问题标题】:How to turn an input text-value into an object's property value in Js?如何将输入的文本值转换为 Js 中对象的属性值?
【发布时间】:2019-07-06 17:11:01
【问题描述】:

我将输入文本值转换为 inp1 var,但是一旦我想在 obj 中调用它,它就不起作用了。

<input type="text" placeholder="Enter your text here" class="input fade-in" id="inp1" required>
 var inp1 = document.getElementById("inp1").value;

$(function(){
  $('#qrcode').qrcode({
    width: 150,
    height: 150,
    text: "https://www.stackoverflow.com/" + inp1
  });
});

我希望 qrcode 代码显示 url + 输入文本

【问题讨论】:

    标签: javascript jquery qr-code


    【解决方案1】:

    您的代码在页面加载时运行一次。那时,输入字段还为空。相反,您可能希望在输入发生变化时 更新二维码。你需要一个事件监听器:

     $(function(){
       var input = $("#inp1"); // if you use jQuery, use it everywhere. Also retrieve the element when the document loaded
    
       input.on("change", function() { // listen for input changes
         $('#qrcode').qrcode({ // then update the qr code
           width: 150,
           height: 150,
           text: "https://www.stackoverflow.com/" + input.val(),
         });
       });
     });
    

    您可能需要考虑使用 input event instead of the change event,具体取决于您的用例。

    【讨论】:

    • 奇怪的是library page 与 OP 正在寻找的示例完全相同
    • 文档中有错误的情况并不少见。
    • @ScottMarcus 该示例运行良好并按预期更新了 qrcode(我的意思是,我实际上并没有扫描它,但我看到它正在改变)
    • @AlonEitan 那不是我正在使用的库。那个库不工作
    • 为什么它给我这个错误:Uncaught SyntaxError: missing ) after argument list
    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多