この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")
以上がjQueryは、あらゆるタイプの入力を動的に設定しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。