Can i (in javascript) write an event or a function that automatically applies to one kind of html tag? [duplicate]

大兔子大兔子 提交于 2019-12-11 06:43:46

问题


I was looking for a way to apply an onclick(); or a function to all the <span></span> tags in my page, even the ones which are created later, like a universal order for all of this type of html tag.

despite of ID class type or any other attribute only tag name.

Edit: Answered by @mhodges by introducing this

note that you should use toLowerCase() too


回答1:


I don't know plain javascript or is jQuery also allowed?

$('body').on('click', 'span', function() {

});

Here a small example

$( document ).ready(function() {
  let i = 1;
  $('button').on('click', function() {
    i++;
    $('#wrapper').append('<span> ' + i + ' </span>');
  });
  
  $('#wrapper').on('click', 'span', function() {
    console.log($(this).text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <span>1</span>
</div>

<button>Add</button>



回答2:


Put a class in them, and then when you use an onclick, you search them with $(".classname")



来源:https://stackoverflow.com/questions/44730431/can-i-in-javascript-write-an-event-or-a-function-that-automatically-applies-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!