in essence the function would contain a jquey selection based on the id that is passed as argument. I recall seeing some code where $x was used to execute jquery as if it was the selection. I want to pass an element id to a function that executes jquery using that selection. sort of like ... doit(elname)
function doit(elname) { $x=???; $x.attr(); etc
CodePudding user response:
Use string interpolation with jQuery selector:
$(`#${idAsParan}`).hide();
Note use of ` character, instead of ' or ". Normally the top left key to the left of '1'.
CodePudding user response:
Consider the following Event based example.
$(function() {
function myFunction(event) {
var $el = $(event.target);
$el.prop("disabled", true);
console.log("Disabled " $el.attr("id"));
}
$("button").click(myFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button-1">Button 1</button>
<button id="button-2">Button 2</button>
<button id="button-3">Button 3</button>
<button id="button-4">Button 4</button>
This uses the event
to select the target. So event.target
is the target element and using $(event.target)
creates it as a jQuery Object.
If you want to pass in a String, you can do that. It might look like this.
$(function() {
function myFunction(elemId) {
var $el;
if (typeof elemId == 'string') {
$el = $("#" elemId);
} else {
$el = $(elemId);
}
$el.prop("disabled", true);
console.log("Disabled " $el.attr("id"));
}
$("button").click(function() {
myFunction($(this).attr("id"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button-1">Button 1</button>
<button id="button-2">Button 2</button>
<button id="button-3">Button 3</button>
<button id="button-4">Button 4</button>