JavaScript不改变网站的背景(完全初学者)

huangapple go评论80阅读模式
英文:

javascript doesn't change background of website (total beginner)

问题

I'm new to javascript and programming in general, I don't know what's going on but for some reason the background image doesn't change with the change of the selected dropdown option.

When I try to test 'dropdownClassMenuRead' with the console output it says '' for some reason.

I'm totally new to programming and web development in general, by the way.

HTML:

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="style.css" rel="stylesheet" type="text/css">

        <title>Talent Point Calculator</title>
    </head>

    <body>
        <select id="dropdownClasses">
            <option>warrior</option>
            <option>mage</option>
            <option>paladin</option>
            <option>rogue</option>
        </select>

        <div id="graphicElements">
            <svg id="svgsection" height="540" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            </svg>
        </div>

        <script src="main.js" defer></script>
    </body>
</html>

JS:

var dropdownClassMenu = document.getElementById('dropdownClasses');
var dropdownClassMenuRead;

const svg_embed = "http://www.w3.org/2000/svg";

dropdownClassMenu.addEventListener('change', function() {
    ChangeBackgroundImage();
});

function checkingSelectedClassDropdownMenu() {
    dropdownClassMenuRead = dropdownClassMenu.options[dropdownClassMenu.selectedIndex].text;
}

// changes the background according to the class dropdown menu
function ChangeBackgroundImage() {
    checkingSelectedClassDropdownMenu();
    var doc = document.getElementById('graphicElements');
    doc.style.backgroundImage = 'url(images/' + dropdownClassMenuRead + '.gif)';
    console.log(doc.style.backgroundImage);
}

CSS:

#graphicElements {
    height: 540px;
    width: 600px;
    background-image: url("images/warrior.gif");
    background-repeat: no-repeat;
    background-color: rgb(132, 132, 132);
    position: absolute;
}
英文:

Im new to javascript and programming in general, I don't know whats going on but for some reason the background image doesn't change with the change of the selected dropdown option.

When I try to test 'dropdownClassMenuRead' with the console output it say '<empty string>' for some reason.

Im total new to programming and web dev in general btw.

HTML:

&lt;html lang=&quot;en&quot;&gt;
	  &lt;head&gt;
			&lt;meta charset=&quot;utf-8&quot;&gt;
			&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
			&lt;link href=&quot;style.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;

			&lt;title&gt;Talent Point Calculator&lt;/title&gt;
		&lt;/head&gt;

	    &lt;body&gt;

		      &lt;select id=&quot;dropdownClasses&quot;&gt;
		        &lt;option&gt;warrior&lt;/option&gt;
		        &lt;option&gt;mage&lt;/option&gt;
		        &lt;option&gt;paladin&lt;/option&gt;
		        &lt;option&gt;rogue&lt;/option&gt;
		      &lt;/select&gt;

					&lt;div id= &quot;graphicElements&quot;&gt;
						&lt;svg id=&quot;svgsection&quot; height=&quot;540&quot; width=&quot;1000&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;
						&lt;/svg&gt;
					&lt;/div&gt;

		    &lt;script src=&quot;main.js&quot; defer&gt;&lt;/script&gt;
				
	    &lt;/body&gt;

JS:

var dropdownClassMenu = document.getElementById(&#39;dropdownClasses&#39;)
var dropdownClassMenuRead;

const svg_embed = &quot;http://www.w3.org/2000/svg&quot;;



dropdownClassMenu.addEventListener(&#39;change&#39;,

function()
    {
        ChangeBackgroundImage();
    }
);


function checkingSelectedClassDropdownMenu()
{
  dropdownClassMenuRead = dropdownClassMenu.options[dropdownClassMenu.selectedIndex].text;
  
}

// changes the background according to the class dropdown menu
function ChangeBackgroundImage()
{
  checkingSelectedClassDropdownMenu();
  var doc = document.getElementById(&#39;graphicElements&#39;);
  doc.style.backgroundImage = &#39;url(images/ + &#39;+dropdownClassMenuRead+&#39; + .gif)&#39;;
  console.log(doc.style.backgroundImage);
}

CSS:

#graphicElements{
  height: 540px;
  width: 600px;
  background-image: url(&quot;images/warrior.gif&quot;);
  background-repeat: no-repeat;
  background-color: rgb(132,132,132);
  position: absolute;


}

答案1

得分: 1

The doc.style.backgroundImage 需要稍微调整,以与JavaScript期望的引号一起使用,需要在 url 前面使用双引号,而在括号内使用单引号。另一种选择是使用模板文字。我在代码中留下了模板文字的注释版本。

注意:我将您的JavaScript更新为利用ES6+,使用let 和箭头函数。这不是必需的,只是建议使用较新的JavaScript标准

let dropdownClassMenu = document.getElementById('dropdownClasses');
let dropdownClassMenuRead;
let doc = document.getElementById('graphicElements');

dropdownClassMenu.addEventListener('change', () => {
  changeBackgroundImage();
});

// 获取 #dropdownClasses 中所选选项的文本
const checkingSelectedClassDropdownMenu = () => {
  dropdownClassMenuRead = dropdownClassMenu.options[dropdownClassMenu.selectedIndex].text;
}

// 根据类别下拉菜单更改背景图像
const changeBackgroundImage = () => {
  checkingSelectedClassDropdownMenu();
  doc.style.backgroundImage = "url('images/" + dropdownClassMenuRead + ".gif')";
  console.log('doc.style.backgroundImage: ', doc.style.backgroundImage);
  
  // 使用模板文字
  // doc.style.backgroundImage = `url('images/${dropdownClassMenuRead}.gif')`;
}
#graphicElements {
  height: 540px;
  width: 600px;
  background-image: url("images/warrior.gif");
  background-repeat: no-repeat;
  background-color: rgb(132, 132, 132);
  position: absolute;
}
<select id="dropdownClasses">
  <option>warrior</option>
  <option>mage</option>
  <option>paladin</option>
  <option>rogue</option>
</select>

<div id="graphicElements">
  <svg id="svgsection" height="540" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>
</div>
英文:

The doc.style.backgroundImage needs to be adjusted a little to work with the quotes that js expects, with double quotes before the url and a single quote inside the parentheses. An alternative is you could use a template literal. I left a commented version of the template literal in the code

Note: I updated your js to take advantage of ES6+ utilizing let and arrow functions. It's not necessary - just recommendation to use newer js standards

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let dropdownClassMenu = document.getElementById(&#39;dropdownClasses&#39;)
let dropdownClassMenuRead;
let doc = document.getElementById(&#39;graphicElements&#39;);

dropdownClassMenu.addEventListener(&#39;change&#39;, () =&gt; {
  changeBackgroundImage();
});

// Get the text of the selected option in #dropdownClasses
const checkingSelectedClassDropdownMenu = () =&gt; {
  dropdownClassMenuRead = dropdownClassMenu.options[dropdownClassMenu.selectedIndex].text;
}

// Changes the background according to the class dropdown menu
const changeBackgroundImage = () =&gt; {
  checkingSelectedClassDropdownMenu();
  doc.style.backgroundImage = &quot;url(&#39;images/&quot; + dropdownClassMenuRead + &quot;.gif&#39;)&quot;;
  console.log(&#39;doc.style.backgroundImage: &#39;, doc.style.backgroundImage);
  
  // Utilizing template literal instead
  // doc.style.backgroundImage = `url(&#39;images/${dropdownClassMenuRead}.gif&#39;)`;
}

<!-- language: lang-css -->

#graphicElements {
  height: 540px;
  width: 600px;
  background-image: url(&quot;images/warrior.gif&quot;);
  background-repeat: no-repeat;
  background-color: rgb(132, 132, 132);
  position: absolute;
}

<!-- language: lang-html -->

&lt;select id=&quot;dropdownClasses&quot;&gt;
  &lt;option&gt;warrior&lt;/option&gt;
  &lt;option&gt;mage&lt;/option&gt;
  &lt;option&gt;paladin&lt;/option&gt;
  &lt;option&gt;rogue&lt;/option&gt;
&lt;/select&gt;

&lt;div id=&quot;graphicElements&quot;&gt;
  &lt;svg id=&quot;svgsection&quot; height=&quot;540&quot; width=&quot;1000&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;&lt;/svg&gt;
&lt;/div&gt;

<!-- end snippet -->

答案2

得分: 0

以下是代码部分的翻译:

As pointed out by **[wouch][1]** the '+' within the first quoted url string is causing this error.  

Actually you can ditch the inner quotes completely like so `url(images/warrior.gif)`.  

If you save image URLs in the `value` attribute, you could get the current  `<select>` value directly via `value` property.  

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

    const  dropdownClassMenu = document.getElementById("dropdownClasses");
    const  doc = document.getElementById("graphicElements");


    dropdownClassMenu.addEventListener("change", (e) => {
      let currentImg = e.currentTarget.value;
      doc.style.backgroundImage = `url(${currentImg})`;
    });

<!-- language: lang-css -->

    #graphicElements{
      height: 540px;
      width: 600px;
      background-image: url(https://picsum.photos/id/237/200/300);
      background-repeat: no-repeat;
      background-color: rgb(132,132,132);
      position: absolute;
    }

<!-- language: lang-html -->

    <select id="dropdownClasses">
      <option value="https://picsum.photos/id/237/200/300">warrior</option>
      <option value="https://picsum.photos/id/236/200/300">mage</option>
      <option value="https://picsum.photos/id/235/200/300">paladin</option>
      <option value="https://picsum.photos/id/234/200/300">rogue</option>
    </select>

    <div id="graphicElements">
      <svg id="svgsection" height="540" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      </svg>
    </div>

<!-- end snippet -->
If you don't wan an additional value attribute, you could still simplify your script by using [template literals][2] e.g. `url(https://picsum.photos/id/${currentImgText}/200/300)` and move the image swap function to the change event listener.  

This way you don't need global variables for the current image URL.  

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

    const dropdownClassMenu = document.getElementById("dropdownClasses");
    const doc = document.getElementById("graphicElements");


    dropdownClassMenu.addEventListener("change", (e) => {
      let currentImgText = e.currentTarget.options[e.currentTarget.selectedIndex].textContent;
      doc.style.backgroundImage = `url(https://picsum.photos/id/${currentImgText}/200/300)`;
    });

    // changes the background according to the class dropdown menu
    function ChangeBackgroundImage() {
      const dropdownClassMenuRead =
        dropdownClassMenu.options[dropdownClassMenu.selectedIndex].value;
      doc.style.backgroundImage = `url(${dropdownClassMenuRead})`;
      console.log(doc.style.backgroundImage);
    }

<!-- language: lang-css -->

    #graphicElements {
      height: 540px;
      width: 600px;
      background-image: url(https://picsum.photos/id/237/200/300);
      background-repeat: no-repeat;
      background-color: rgb(132, 132, 132);
      position: absolute;
    }

<!-- language: lang-html -->

    <select id="dropdownClasses">
      <option>237</option>
      <option>236</option>
      <option>235</option>
      <option>234</option>
    </select>

    <div id="graphicElements">
      <svg id="svgsection" height="540" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      </svg>
    </div>

<!-- end snippet -->

希望这有所帮助。如果您需要更多信息,请随时提问。

英文:

As pointed out by wouch the '+' within the first quoted url string is causing this error.

Actually you can ditch the inner quotes completely like so url(images/warrior.gif).

If you save image URLs in the value attribute, you could get the current &lt;select&gt; value directly via value property.

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

const  dropdownClassMenu = document.getElementById(&quot;dropdownClasses&quot;);
const  doc = document.getElementById(&quot;graphicElements&quot;);


dropdownClassMenu.addEventListener(&quot;change&quot;, (e) =&gt; {
  let currentImg = e.currentTarget.value;
  doc.style.backgroundImage = `url(${currentImg})`;
});

<!-- language: lang-css -->

#graphicElements{
  height: 540px;
  width: 600px;
  background-image: url(https://picsum.photos/id/237/200/300);
  background-repeat: no-repeat;
  background-color: rgb(132,132,132);
  position: absolute;
}

<!-- language: lang-html -->

&lt;select id=&quot;dropdownClasses&quot;&gt;
  &lt;option value=&quot;https://picsum.photos/id/237/200/300&quot;&gt;warrior&lt;/option&gt;
  &lt;option value=&quot;https://picsum.photos/id/236/200/300&quot;&gt;mage&lt;/option&gt;
  &lt;option value=&quot;https://picsum.photos/id/235/200/300&quot;&gt;paladin&lt;/option&gt;
  &lt;option value=&quot;https://picsum.photos/id/234/200/300&quot;&gt;rogue&lt;/option&gt;
&lt;/select&gt;

&lt;div id=&quot;graphicElements&quot;&gt;
  &lt;svg id=&quot;svgsection&quot; height=&quot;540&quot; width=&quot;1000&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;
  &lt;/svg&gt;
&lt;/div&gt;

<!-- end snippet -->

If you don't wan an additional value attribute, you could still simplify your script by using template literals e.g. url(https://picsum.photos/id/${currentImgText}/200/300) and move the image swap function to the change event listener.

This way you don't need global variables for the current image URL.

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

const dropdownClassMenu = document.getElementById(&quot;dropdownClasses&quot;);
const doc = document.getElementById(&quot;graphicElements&quot;);


dropdownClassMenu.addEventListener(&quot;change&quot;, (e) =&gt; {
  let currentImgText = e.currentTarget.options[e.currentTarget.selectedIndex].textContent;
  doc.style.backgroundImage = `url(https://picsum.photos/id/${currentImgText}/200/300)`;
});

// changes the background according to the class dropdown menu
function ChangeBackgroundImage() {
  const dropdownClassMenuRead =
    dropdownClassMenu.options[dropdownClassMenu.selectedIndex].value;
  doc.style.backgroundImage = `url(${dropdownClassMenuRead})`;
  console.log(doc.style.backgroundImage);
}

<!-- language: lang-css -->

#graphicElements {
  height: 540px;
  width: 600px;
  background-image: url(https://picsum.photos/id/237/200/300);
  background-repeat: no-repeat;
  background-color: rgb(132, 132, 132);
  position: absolute;
}

<!-- language: lang-html -->

&lt;select id=&quot;dropdownClasses&quot;&gt;
  &lt;option&gt;237&lt;/option&gt;
  &lt;option&gt;236&lt;/option&gt;
  &lt;option&gt;235&lt;/option&gt;
  &lt;option&gt;234&lt;/option&gt;
&lt;/select&gt;

&lt;div id=&quot;graphicElements&quot;&gt;
  &lt;svg id=&quot;svgsection&quot; height=&quot;540&quot; width=&quot;1000&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;
  &lt;/svg&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月21日 01:37:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定