2017-02-09 81 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");