【问题标题】:How to use a value as a name of a file?如何使用值作为文件名?
【发布时间】:2022-08-02 14:49:24
【问题描述】:

我是 JS 的新手。我想通过使用标签中的值来更改 div 的背景图像。我可以更改背景颜色,但现在我想将该值用作 jpg 文件的名称。有谁知道怎么做?值将是 1、2、3,图形文件的名称是 1.jpg、2.jpg 和 3.jpg。

   <div class=\"container\" id=\"wrapper\">
      <form>
        <label for=\"my-select\">Choose the continent:    </label>
        <select
          name=\"\"
          id=\"my-select\"
          value=\"Choose the continent\"
          onChange=\"myFunction()\"
        >
          <option value=\"default\">default</option>
          <option value=\"1\">Asia</option>
          <option value=\"2\">Australia</option>
          <option value=\"3\">South america</option>
        </select>
      </form>
    </div>
  const myWrapper = document.querySelector(\"#wrapper\");

  function myFunction() {
  var x = document.getElementById(\"my-select\").value;
  myWrapper.style.backgroundImage = url(\"images/x.jpg\");
  }
  // I know the last line won\'t work. 

    标签: javascript


    【解决方案1】:

    你很接近,尝试这样的事情:

      const myWrapper = document.querySelector("#wrapper");
    
      function myFunction() {
      var x = document.getElementById("my-select").value;
      myWrapper.style.backgroundImage = "url(images/" + x + ".jpg)";
      }
       <div class="container" id="wrapper">
          <form>
            <label for="my-select">Choose the continent:    </label>
            <select
              name=""
              id="my-select"
              value="Choose the continent"
              onChange="myFunction()"
            >
              <option value="default">default</option>
              <option value="1">Asia</option>
              <option value="2">Australia</option>
              <option value="3">South america</option>
            </select>
          </form>
        </div>

    【讨论】:

      【解决方案2】:

      您可以为此使用template literals

      myWrapper.style.backgroundImage = url(`images/${x}.jpg`);
      

      【讨论】:

        【解决方案3】:

        您的解决方案大多是正确的。您只需将整个字符串插入到 CSS 样式中,就像在 CSS 中通常那样。

        然后,您需要将 X-Value 连接到字符串,因此它获取存储在其中的数字而不是 x 作为直接字符。

        const myWrapper = document.querySelector("#wrapper");
        
        function myFunction() {
          var x = document.getElementById("my-select").value;
        
          // You'll need to insert the CSS-Style as an entire string.
          // We concatenate the Variable X to the string, so it gets dynamicly used.
          myWrapper.style.backgroundImage = "url('images/"+x+".jpg')";
        } 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多