问题
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