javascript addEventListener不能多次使用 [英] javascript addEventListener not working more than once

查看:94
本文介绍了javascript addEventListener不能多次使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个相对简单的javascript程序/页面,只有3个滑块RGB会影响正方形和圆形的颜色。



当我使用输入元素的事件监听器'inline'时,它工作得很好:即, onchange =someFunction(x,y)



然而,当我将事件监听器移动到javascript中时,使用 addEventListener ,它只在页面加载时起作用,然后再也不起作用......几乎好像已经调用了 removeEventListener ,但我还没有这样做。 / p>

是的,我确保在调用javascript之前所有元素都已加载到页面上。



我有修改此代码只是为了给我一个ALERT而不是实际调用我想要的函数 slideUpdate ,仅用于调试目的。



这是:
JAVASCRIPT:

  var colorBox = document.getElementById(colorbox); 
var colorCircle = document.getElementById(colorCircle);
var colorPicker = document.getElementById(colorPicker);
var sliderRed = document.getElementById(Red);
var sliderGreen = document.getElementById(Green);
var sliderBlue = document.getElementById(Blue);

//sliderRed.addEventListener(\"onchange,alertForDebug());
//sliderRed.addEventListener(\"onclick,alert(sliderRed.value));

document.addEventListener('DOMContentLoaded',function(){
alert(document loaded!);
sliderRed.addEventListener(change,alert(sliderRed.value) ));
//document.querySelector('#Red').addEventListener('change',slideUpdate(sliderRed.value,sliderRed.id));
//document.querySelector('#Green ')。addEventListener('onchange',slideUpdate(this.value,this.id));
//document.querySelector('#Blue').addEventListener('onchange',slipUpdate( this.value,this .id));
});

函数slideUpdate(value,elementID){
alert(slideUpdate(+ value +,+ elementID +));
//console.log(\"function slideMe()达到.value =+ value +elementID =+ elementID);
//rangeSlider.innerHTML =Value =; // + rangeSlider.value;
//document.getElementById(elementID).innerText =Value =+ value;
//elementID.innerText = value;
//console.log(elementID +Display);
document.getElementById(elementID +Display)。innerHTML =Value =+ value; //每次使用变量代替getElementById可以这样做

//现在更新颜色框以反映当前颜色
var currentColor = colorBox.style.backgroundColor;
var splitString = currentColor.split(,);
var red = parseInt(splitString [0] .slice(4)); //不要rgb(在那里
var green = splitString [1];
var blue = parseInt(splitString [2]);
var newColor =rgb( ; //不完整的
console.log(currentColor +value =+ value);
console.log(splitString =+ splitString);
console.log(old color red =+ red +green =+ green +blue =+ blue);

switch(elementID){
caseRed:
// alert(红色);
newColor =rgb(+ value.toString()+,+ green +,+ blue;
red = value;
break;
caseGreen:
newColor =rgb(+ red +,+ value.toString()+,+ blue;
green = value;
break;
caseBlue:
newColor =rgb(+ red +,+ green +,+ value.toString()+);
blue = value;
break ;
}

//console.log(value.toString(16));
colorBox.style.backgroundColor = newColor;
colorCircle.style.fill = newColor;
console.log(new color red =+ red +green =+ green +blue =+ blue);
var convertedColor = rgbToHex(红色,绿色,蓝色);
colorPicker.value = convertedColor;
console.log(convertedColor =+ convertedColor);
}

/ *
函数rgbToHex(红色,绿色,蓝色){
var rgb = blue | (绿色<< 8)| (红色<< 16);
返回'#'+(0x1000000 + rgb).toString(16).slice(1);
//返回'#'+ rgb.toString(16)
} * /

/ *函数rgbToHex(r,g,b){
if( r< 0 || r> 255)警报(r超出范围;+ r);
if(g< 0 || g> 255)alert(g超出界限;+ g);
if(b< 0 || b> 255)alert(b超出范围;+ b);
返回#+((1 << 24)+(r< 16)+(g << 8)+ b).toString(16).slice(1,7) );
} * /

函数hexstr(数字){
var chars = new Array(0,1,2,3,4 ,5,6,7,8,9,a,b,c,d,e,f);
var low = number& 0xf;
var high =(number>> 4)& 0xf;
返回+字符[高] +字符[低];
}

函数rgbToHex(r,g,b){
返回#+ hexstr(r)+ hexstr(g)+ hexstr(b);
}

函数updateColor(newColor){
console.log(newColor);
colorBox.style.backgroundColor = newColor;
colorCircle.style.fill = newColor;
colorPicker.value = newColor;

var red = parseInt(0x+ newColor.slice(1,3));
var green = parseInt(0x+ newColor.slice(3,5));
var blue = parseInt(0x+ newColor.slice(5));

//现在更新滑块
document.getElementById(Red)。value = red;
document.getElementById(Green)。value = green;
document.getElementById(Blue)。value = blue;
document.getElementById(RedDisplay)。innerHTML =Value =+ red;
document.getElementById(GreenDisplay)。innerHTML =Value =+ green;
document.getElementById(BlueDisplay)。innerHTML =Value =+ blue;
}

HTML文件:

 <!DOCTYPE HTML> 

< HTML>

< head>
< p align =center>光控制器< / p>
< / head>

< body>

< p>使用滑块控制下面彩色显示的光R,G,B值。< / p>

< div>
< label for =Red> Red 0
< input type =rangeID =Redmin = 0 max = 255>< / input>
255
< label ID =RedDisplay> Value =< / label>

< / label>

< / div>
< div>
< label for =Green> Grn 0
< input type =rangeID =Greenmin = 0 max = 255>< / input>
255< label ID =GreenDisplay>值= LT; /标签>< /标签>
< / div>

< div>
< label for =Blue> Blu 0
< input type =rangeID =Bluemin = 0 max = 255>< / input>
255< label ID =BlueDisplay>值= LT; /标签>< /标签>
< / div>

< / body>


< input id =colorboxSTYLE =background-color:#FF0000;>< / input>



< svg width =100height =100>
< circle id =colorCirclecx =50cy =50r =40stroke =黑色stroke-width =4fill =yellow/>
对不起,您的浏览器不支持内联SVG。
< / svg>

< input type =colorid =colorPickeronchange =updateColor(this.value)>< / input>

< script src =LiteCntrlMain.js>< / script>


解决方案

addEventListener 将一个函数引用作为它的第二个参数。在这里,你试图添加它时直接调用该函数。这应该适合你:

  document.addEventListener('DOMContentLoaded',function(){
alert(document loaded!);
sliderRed.addEventListener(change,function( ){alert(sliderRed.value)});
//包裹在一个函数中
});

您必须将此模式应用于所有活动。


I'm trying to do a relatively simple javascript program/page, just 3 sliders RGB to affect the color of a square and circle.

It works GREAT when I have the event listeners 'inline' with the input elements: i.e., onchange="someFunction(x,y)"

However, when I move the event listeners to be in the javascript, and use addEventListener, it only works ONCE when the page loads, and then never again...almost as if a removeEventListener has been called, but I haven't done that.

Yes, I made sure that all elements are loaded on the page before I call the javascript.

I have altered this code to just give me an ALERT instead of actually calling my desired function slideUpdate, just for debugging purposes.

Here it is: JAVASCRIPT:

var colorBox = document.getElementById("colorbox");
var colorCircle = document.getElementById("colorCircle");
var colorPicker = document.getElementById("colorPicker");
var sliderRed = document.getElementById("Red");
var sliderGreen = document.getElementById("Green");
var sliderBlue = document.getElementById("Blue");

//sliderRed.addEventListener("onchange", alertForDebug() );
//sliderRed.addEventListener("onclick", alert(sliderRed.value) );

document.addEventListener('DOMContentLoaded', function () {
    alert("document loaded!");
    sliderRed.addEventListener("change", alert(sliderRed.value) );
    //document.querySelector('#Red').addEventListener('change', slideUpdate(sliderRed.value, sliderRed.id) );
    //document.querySelector('#Green').addEventListener('onchange', slideUpdate(this.value, this.id) );
    //document.querySelector('#Blue').addEventListener('onchange', slideUpdate(this.value, this.id) );
} );

function slideUpdate(value, elementID) {
    alert("slideUpdate("+value+","+elementID+")");
    //console.log("function slideMe() reached. value=" + value + " elementID="+elementID);
    //rangeSlider.innerHTML = "Value=";// + rangeSlider.value;
    //document.getElementById(elementID).innerText = "Value=" + value;
    //elementID.innerText = value;
    //console.log(elementID + "Display");
    document.getElementById(elementID+"Display").innerHTML = "Value=" + value; //could do this using variables instead of  getElementById each time

    //now update the color box to reflect current color
    var currentColor = colorBox.style.backgroundColor;
    var splitString = currentColor.split(",");
    var red = parseInt(splitString[0].slice(4));  //don't the "rgb(" in there
    var green = splitString[1];
    var blue = parseInt(splitString[2]);
    var newColor = "rgb("; //incomplete
    console.log(currentColor + "value = " + value);
    console.log("splitString=" + splitString);
    console.log("old color red="+red +"    green="+green+"    blue="+blue);

    switch(elementID) {
    case "Red":
        //alert("Red");
        newColor = "rgb("+value.toString()+","+green+","+blue;
        red=value;
        break;
    case "Green":
        newColor = "rgb("+red+","+value.toString()+","+blue;
        green=value;
        break;
    case "Blue":
        newColor = "rgb("+red+","+green+","+value.toString()+")";
        blue=value;
        break;
    }

    //console.log(value.toString(16));
    colorBox.style.backgroundColor = newColor;
    colorCircle.style.fill = newColor;
    console.log("new color red="+red +"    green="+green+"    blue="+blue);
    var convertedColor = rgbToHex(red, green, blue);
    colorPicker.value = convertedColor;
    console.log("convertedColor="+convertedColor);
}

/*
function rgbToHex(red, green, blue) {
    var rgb = blue | (green << 8) | (red << 16);
    return '#' + (0x1000000 + rgb).toString(16).slice(1);
    //return '#' + rgb.toString(16)
}*/

/*function rgbToHex(r, g, b) {
    if(r < 0 || r > 255) alert("r is out of bounds; "+r);
    if(g < 0 || g > 255) alert("g is out of bounds; "+g);
    if(b < 0 || b > 255) alert("b is out of bounds; "+b);
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}*/

function hexstr(number) {
    var chars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
    var low = number & 0xf;
    var high = (number >> 4) & 0xf;
    return "" + chars[high] + chars[low];
}

function rgbToHex(r, g, b) {
    return "#" + hexstr(r) + hexstr(g) + hexstr(b);
}

function updateColor(newColor) {
    console.log(newColor);
colorBox.style.backgroundColor = newColor;
colorCircle.style.fill = newColor;
colorPicker.value = newColor;

var red = parseInt("0x"+newColor.slice(1,3));
var green = parseInt("0x"+newColor.slice(3,5));
var blue = parseInt("0x"+newColor.slice(5));

//now update the sliders
document.getElementById("Red").value= red;
document.getElementById("Green").value= green;
document.getElementById("Blue").value= blue;
document.getElementById("RedDisplay").innerHTML = "Value=" + red;
document.getElementById("GreenDisplay").innerHTML = "Value=" + green;
document.getElementById("BlueDisplay").innerHTML = "Value=" + blue;
}

HTML file:

<!DOCTYPE HTML>

<HTML>

<head>
<p align="center"> Light Controller</p>
</head>

<body>

<p>Use the sliders to control the light R,G,B values for color displays below.</p>

<div>
<label for="Red">Red 0
  <input type="range" ID="Red" min=0 max=255 ></input>
255 
<label ID="RedDisplay">Value=</label>

</label>

</div>
<div>
<label for="Green">Grn 0
  <input type="range" ID="Green" min=0 max=255></input>
255 <label ID="GreenDisplay"> Value=</label></label>
</div>

<div>
<label for="Blue">Blu 0
  <input type="range" ID="Blue" min=0 max=255></input>
255 <label ID="BlueDisplay"> Value=</label></label>
</div>

</body>


<input id="colorbox" STYLE="background-color: #FF0000;""></input>



<svg width="100" height="100">
   <circle id="colorCircle" cx="50" cy="50" r="40" stroke="black" stroke-width="4" fill="yellow" />
   Sorry, your browser does not support inline SVG.
</svg> 

<input type="color" id="colorPicker" onchange="updateColor(this.value)"></input>

<script src="LiteCntrlMain.js"></script>

解决方案

addEventListener takes a function reference as its second parameter. Here, you're directly calling the function when you try to add it. This should work for you:

document.addEventListener('DOMContentLoaded', function () {
    alert("document loaded!");
    sliderRed.addEventListener("change", function(){alert(sliderRed.value)} );
    // wrapped in a function
} );

You'll have to apply this pattern to all of your events.

这篇关于javascript addEventListener不能多次使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆