【问题标题】:Add Event Listener for a DIV whenever it appear on page?每当 DIV 出现在页面上时为其添加事件侦听器?
【发布时间】:2019-12-27 16:54:50
【问题描述】:

类似于 addEventListener("click"),但不是点击事件,而是我想更改 addEventListener("Is there abc DIV on page?")

document.addEventListener("Is there abc DIV on page?"){
   If yes{
       console.log("yes, there is abc div on page");
   }
   else{
       console.log("no, there is no abc div on page");
   }
}

//User can toggle the presence of abc div whenever they want
document.addEventListener("click/keyboard/...."){
     Remove abc div or Add abc div;
}

每次用户切换 abc div 的存在时,此事件侦听器都会捕获并注意到更改。

谢谢

【问题讨论】:

标签: javascript


【解决方案1】:

可能是这样的:

      function add_abc_div(){
      	 var abc = document.getElementById('abc');
      	 if(abc){
      	 	alert('ABC div already exist!');
      	 	return false;
      	 }
      	 var test = document.getElementById('test');
      	 test.innerHTML = test.innerHTML + '<div id="abc">this is ABC div</div>';
      }
      function remove_abc_div(){
      	 var abc = document.getElementById('abc');
      	 if(abc){
      	 	 abc.remove();
      	 }
      }
      function my_event(){
      	 var abc = document.getElementById('abc');
      	 if(!abc){
      	 	alert('not found ABC');
      	 }else{
      	    alert('found ABC');
      	 }
      }
      document.getElementById('test').addEventListener('click', my_event, false);
        #test{
        	border-style: solid;
        	border-width: 1px;
        	height: 100px;
        	width: 100px;
        	text-align: center;
        	cursor: pointer;
        }
        #abc{
        	background-color : gray;
        }
<div id="test">Click Me!</div>
<input type="button" value="add ABC div" onclick="add_abc_div()" /></br>
<input type="button" value="remove ABC div" onclick="remove_abc_div()" />

【讨论】:

  • 谢谢,但这个解决方案不是我的问题,事件监听器应该自动检查 ABC Div,而不是点击检查!
【解决方案2】:

“页面上的 div”是指“显示”、“在 DOM 中创建”还是两者兼而有之?

页面上的 Div > 显示

我只会得到 div.style.displayed 值。

页面上的 Div > 在 DOM 中创建

在创建 div 时,我会给它一个特定的类或数据值。

<div class="specific-div" style="display:none"></div>

const isDisplayed = document.getElementsByClassName('specific-div')[0].style.display !== 'none';
// or
const divs = document.getElementsByClassName('specific-div');
divs.forEach(div => doSomething());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多