jQuery(#id).val() vs. getElementById(#id).value

前端 未结 7 945
眼角桃花
眼角桃花 2020-12-01 16:02

I been searching but I can only find articles talking about one or the other. Which one is better?

I\'m making a small web app where performance is not a big concern

7条回答
  •  执念已碎
    2020-12-01 16:33

    Here https://www.dyn-web.com/tutorials/forms/checkbox/same-name-group.php is an implementation for checkboxes, apparently options just need to be named the same with the array brackets notation in the name i.e.: name="sport[]" then yu get the array inJavascript via: var sports = document.forms['demoForm'].elements['sport[]']

    I was looking for a selection type field solution without using jQuery and I came across this solution:

    The Selection group is an object: HTMLCollection, and it has a lenght method and a selectedOptions property, which allows you to iterate through its label properties to populate an Array with the selected options, which then you can use:

    ...
        vehicleCol = document.getElementById('vehiculo').selectedOptions;
        vehiculos  = [];
    
        if (vehicleCol !== undefined) {
            for (let i = 0; i < vehicleCol.length; i++) {
                vehiculos.push(vehicleCol[i].label.toLowerCase())
            }
        }
    ...
    

提交回复
热议问题