简体   繁体   中英

Passing parameters in a jQuery variable

I've been away from jQuery development and all js in general for about three years. I can not for the life of me remember how this is supposed to work. This has been going on for four days, and I could really use some help. Can you tell me what I am doing wrong here:

var $imgAll = $(function(f, a) {
    '<img src="' + f + ' alt=&quot' + a + '">';
});

var $imgAC = $imgAll('filename1.jpg', 'Some Alt Text');
var $imgBC = $imgAll('filename2.jpg', 'Some Alt Text');

$page.append($imgAC);

I want an output of code for images whose filenames (f) and alt texts (a) are passed using a single function. It looks like Greek at this point because I'm staring at it constantly.

Thanks for any help!

You'll want $imgAll to be a function, not the return value of a call of $ . Here is how it could work:

 var $imgAll = function(src, alt) { return $('<img>').attr({src, alt}); } var $imgAC = $imgAll('https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg', 'Some Alt Text'); $("body").append($imgAC);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Note how the call to attr avoids building the attribute strings yourself, and thereby the potential problems with characters that need escaping. Also, by naming the function parameters as the attribute names ( src and alt ) you can use the short object literal notation. You could even use an arrow function expression:

const $imgAll = (src, alt) => $('<img>').attr({src, alt});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM