簡體   English   中英

Javascript選擇器:引用子函數中的選定項

[英]Javascript selectors: reference selected item in child function

我有一個大約 50 個輸入的表格。 我已經用一個類選擇器初始化了它們

 <input class="common-class" id="firstname" value="Some data"> <input class="common-class" id="lastname" value="Some data">

我有一個任意插件(編輯器),它將對內容執行操作。 我需要知道哪個輸入被觸摸了。

 function arbitraryPluginFunction(input) { /*Plugin doing whatever it has to do */ input.callback(); } $(document).ready(function() { $(".common-class").arbitraryPluginFunction({ initsetting1: "sample", initsetting2: "sample", callback: function() { console.log("You changed : " + $(this).attr("id")); }, }); });

請注意我的示例中的錯誤,因為 $(this).attr() 指的是傳遞給插件的對象。 我有一個使用 $.each 的不優雅的解決方法,但想知道是否有一些正確的方法。

*** 編輯 *** 這是更接近實際通話的內容。 我從我的問題中刪除了編輯器以簡化

 $(document).ready(function() { $(".common-class").redactor({ changeCallback: function() { console.log("You changed : " + $(this).attr("id")); }); }); });

除非我遺漏了什么,否則您可以將選擇器傳遞給 jquery 函數,它將將該函數應用於所有匹配的元素。

然后你創建你的函數,比如$.fn.redactor並且在函數中$(this)將對應於選定的元素。

 $(document).ready(function() { $.fn.redactor = function(p){ $(this).on("input",function(){ p.changeCallback($(this).attr("id")); }); } $(".common-class").redactor({ changeCallback: function(id) { console.log("You changed : " + id); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="common-class" id="firstname" value="Some data"> <input class="common-class" id="lastname" value="Some data">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM