【问题标题】:Passing variables to text javascript?将变量传递给文本javascript?
【发布时间】:2015-02-12 09:29:18
【问题描述】:

我试图将 3 个变量传递给一个主变量,然后将其放入文本中,代码中不起作用的部分是文本:“+won+”,有人知道如何修复这部分吗?一点额外的东西,这样你就可以理解我在做什么......所有的变量都将在名为 quote 的 div 中显示为文本。

var w = "W";
var o = "o";
var n = "n";

var won1 = w + o + n;


(function() {
      var quotes = [
        {
          text: "+won+",
          img:  "http://i.stack.imgur.com/FqBE6.jpg?s=32&g=1"
        },
        {
          text: "+won+",
          img:  "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG"
        }

      ];
      var quote = quotes[Math.floor(Math.random() * quotes.length)];
      document.getElementById("quote").innerHTML =
       '<center>' + '<p>' + quote.text + '</p>' +
        '<img src="' + quote.img + '">' + '</center>';
    })();

发生了什么: 发生的事情是它没有得到变量,例如如果我输入 +won1+ 它显示文本“+won1+”而不是读取“won”的变量 非常感谢阅读:)

【问题讨论】:

  • 试试text: won 而不是text: "+won+"
  • 为什么在你的问题上使用 jQuery 标签?仅供参考,&lt;center&gt; 元素不再存在。
  • 定义“不起作用”。正在发生什么,您预计会发生什么?
  • 我正在尝试它在标题中所说的内容以及代码中显示的内容,如果我输入 +won1+,它不会得到例如 vars,它会显示文本“+won1+”而不是读作“赢”的变量
  • 当您输入+won1+ 时,您期待什么?正如 Oriol 所说,你试过 won, 吗?

标签: javascript variables var


【解决方案1】:

试试这样的:

var w = "W";
    var o = "o";
    var n = "n";

    var won = w + o + n;


    (function() {
          var quotes = [
            {
              text: won,// if you want to get displayed text as won1 use,text:won+1,
              img:  "http://i.stack.imgur.com/FqBE6.jpg?s=32&g=1"
            },
            {
              text: won,
              img:  "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG"
            }

          ];
          var quote = quotes[Math.floor(Math.random() * quotes.length)];
          console.log(quote);
          document.getElementById("quote").innerHTML =
           '<center>' + '<p>' + quote.text + '</p>' +
            '<img src="' + quote.img + '">' + '</center>';
        })();
&lt;p type="text" id="quote" value="Test value"&gt;&lt;/p&gt;

【讨论】:

  • @user3112634 试试这个答案。
【解决方案2】:

var w = "W";
var o = "o";
var n = "n";

var won1 = w + o + n;


(function() {
  var quotes = [{
      text: won1,
      img: "http://i.stack.imgur.com/FqBE6.jpg?s=32&g=1"
    }, {
      text: won1,
      img: "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG"
    }

  ];
  var quote = quotes[Math.floor(Math.random() * quotes.length)];
  document.getElementById("quote").innerHTML =
    '<center>' + '<p>' + quote.text + '</p>' +
    '<img src="' + quote.img + '">' + '</center>';
})();
&lt;div id="quote"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2012-01-28
    • 2012-10-24
    • 2021-04-21
    • 2019-03-24
    • 2021-04-16
    相关资源
    最近更新 更多