简体   繁体   中英

Passing object HTMLInputElement as a parameter to function

I am trying to pass a DOM element to a function without any luck. FireBug reports the following issue:

SyntaxError: missing ] after element list
LlenarDetalleReserva([object HTMLInputElement]); return false;

The selector needs to add a few attributes dynamically as it's being created.

I've tried the following:

$('#mySelector').attr({'onkeydown' : 'intOrFloat(event,this.value);', 'onchange' : 'LlenarDetalleReserva('+ $.trim($('#cant_r_'+ vectorid[2])[0]) +'); return false;'});

What am I missing here? What is producing this error?

Thanks in advance.

Please, don't do that. Use on() to bind an event to the element. Never set it as an attribute directly.

$('#mySelector')
    .on('keydown', function(event) 
    {
        intOrFloat(event, this.value);
    })
    .on('change', function(event) 
    {
        if (vectorid && vectorid[2] != undefined)
        {
            var element = $('#cant_r_'+ vectorid[2]);

            if (element.length > 0)
            {
                LlenarDetalleReserva(element); 
            }
        }

        return false;
    });

The code above(full of if s) is made to avoid exceptions at run-time. That is what I would do in your case. Further, I don't really know what you're trying to get in that $.trim() function, but it seems that you want to get the element and pass it as a string. In the code above its being passed by reference, instead.

UPDATE:

In order to answer OP's question of why I shouldn't set an attribute directly I didn't tell you you can't add an attribute directly but an event handler as attribute.I can't tell what happens in the backgrounds of the engine, so in fact, it works adding as attribute. But isn't a best practice and it's part of Unobtrusive approach.

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