2017-02-09 100 views
0

我創建了一個JavaScript函數如下所示:jQuery函數作爲對象

function highlight_input() { 
    $("input").css("background", "yellow"); 
} 

$("#input1").highlight_input(); 
$("#input2").highlight_input(); 

現在我想的時候,要突出兩個輸入類型!但是兩者都不應該一次突出顯示!

+1

請解釋你想要做得更清楚。你什麼意思「當你需要」? – Soviut

回答

5

您可以通過在jQuery.fn(擴展jQuery原型)中添加函數來創建basic plugin,其中this引用函數內部的jQuery對象。

jQuery.fn.highlight_input = function() { 
 
    // here this refers to the jQuery object , so 
 
    // you can apply jQuery methods without wrapping 
 
    this.css("background", "yellow"); 
 
    // return the object reference to keep chaining 
 
    return this; 
 
} 
 

 
$("#input1").highlight_input(); 
 
$("#input2").highlight_input();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input1"> 
 
<input id="input2"> 
 
<input>


即使你可以通過顏色如果你想在某些情況下,應用自定義顏色參數。

jQuery.fn.highlight_input = function(color) { 
 
    // if argument is undefined use the default value 
 
    // although you can return in the same line since 
 
    // css method returns the object reference 
 
    return this.css("background", color || "yellow"); 
 
} 
 

 
$("#input1").highlight_input(); 
 
// passing color as argument 
 
$("#input2").highlight_input("red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input1"> 
 
<input id="input2"> 
 
<input>

+0

你走在正確的道路上,但不是正確的道路。閱讀並調整你的答案。 https://api.jquery.com/jquery.fn.extend/ –

+0

另外,請記住,做一個jq選擇器可能會返回你和對象數組。 –

+1

@DincaAdrian:extend正在使用添加多個屬性....它提供了相同的行爲 –

0

jQuery插件將做的工作

$.fn.highlight_input = function(){ 
    return this.css({background:"yellow"}); 
} 

,你還可以通過所需的顏色參數(這將回退到黃

$.fn.highlight_input = function(color) { 
    return this.css({background: color||"yellow"}); 
} 

使用像

$("selector").highlight_input("#f80");