這個jQuery插件簡化了動態的各種輸入類型的設置值。 它通過提供單個函數來解決不同輸入類型(文本,選擇,複選框,收音機等)的不同方法的問題。
>
問題:
>動態設置表單輸入值需要不同的方法,具體取決於輸入類型。 該插件旨在將它們合併到一個可重複使用的功能中。
>解決方案:
$.fn.field
插件提供了一種統一的方法,以獲取和設置表單中任何輸入類型的值。
用法:
>通過傳遞表單的jQuery元素,輸入名稱和值來使用插件。 例如:
$('#myForm').field('name', 'John Doe'); // Text input $('#myForm').field('country', 'USA'); // Select $('#myForm').field('newsletter', true); // Checkbox $('#myForm').field('gender', 'male'); // Radio button
完整代碼:
(function () { $.fn.field = function (inputName, value) { if (typeof inputName !== "string") return false; const $inputElement = this.find(`[name="${inputName}"]`); if (typeof value === "undefined" && $inputElement.length >= 1) { switch ($inputElement.attr("type")) { case "checkbox": return $inputElement.is(":checked"); case "radio": let result; $inputElement.each(function () { if ($(this).is(":checked")) result = $(this).val(); }); return result; default: return $inputElement.val(); } } else { switch ($inputElement.attr("type")) { case "checkbox": $inputElement.prop("checked", value); // Use prop for boolean attributes break; case "radio": $inputElement.each(function () { if ($(this).val() == value) $(this).prop("checked", true); // Use prop for boolean attributes }); break; case undefined: // Handle cases where the element isn't an input this.append(''); // Or handle appropriately for your use case break; default: $inputElement.val(value); break; } return $inputElement; } }; })();
改進:>
使用模板文字進行清潔字符串串聯。.prop("checked")
.attr("checked")
包括case undefined
以上是任何類型的輸入的jQuery設置值的詳細內容。更多資訊請關注PHP中文網其他相關文章!