I have this piece of code:
$('#btn_1, #btn_2').on('click', function() {
// Button 1
let btn1conSpan = $('#btn_1 span');
// Button 2
let btn2conSpan = $('#btn_2 span');
console.log(btn1conSpan.text());
console.log(btn2conSpan.text());
});
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<button id="btn_1"><span>Span1</span> Button 1</button>
<button id="btn_2"><span>Span2</span> Button 2</button>
Which works correctly, now my question, is when I want to use the $(this)
selector:
Is it possible in some way to know which of the id
's has been pressed ( without using conditions ( if ( .. )
))? In such a way that it shows the result as the first example?
The second example shows the idea I have, but obviously does not give the desired result:
$('#btn_1, #btn_2').on('click', function(){
let $this = $(this);
// Button 1
let btn1conSpan = $this.find('span'); // Que sea el selector #btn_1
// Button 2
let btn2conSpan = $this.find('span'); // Que sea el selector #btn_2
console.log(btn1conSpan.text()); // Resultado deseado: Span1
console.log(btn2conSpan.text()); // Resultado deseado: Span2
});
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<button id="btn_1"><span>Span1</span> Button 1</button>
<button id="btn_2"><span>Span2</span> Button 2</button>
The desired result of example 2 is:
Span1
Span2
EDIT :
I see that it is somewhat confusing to understand the question.
Simplify as much as possible:
$('#btn_1, #btn_2').on('click', function() {
// Quiero seleccionar con $(this) de esta forma
$(this).elemento1; // Que sea #btn_1
$(this).elemento2; // Que sea #btn_2
});
Is there a way to make it that simple?