在JQuery中创建函数以避免再次编写相同的代码 [英] Creating Functions in JQuery to Avoid Writing the Same Code Again
问题描述
我目前使用Twitch API接收关于特定频道的信息,然后将其前置到HTML文档。预先反映信息的代码被反复使用。我想知道你是如何创建一个可以避免重复并在文档中被调用的函数的?
可以在这里找到codepen: http://codepen.io/sibraza/pen/AXRRvq
这是重复使用的JQuery代码:
$(#follower-Info)。prepend(< div class ='row'>+< div class ='col-md-4'>+< img src ='+ logo +'>+< / div> +< div class ='col-md-4'>+ name +< / div>+< div class ='col-md-4'>+ status +< / div>< / div>)
类似这样的工作:
function addThis(){
$(#follower-Info)。prepend(< div class = 'row'>+< div class ='col-md-4'>+< img src ='+ logo +'>+< / div& < div class ='col-md-4'>+ name +< / div >+< div class ='col-md-4'>+ status +< / div>< / div>)
}
然后我可以在每个$ .getJSON请求之后调用addThis()。
它会工作,但您需要传递名称
,徽标
和 status
作为函数的参数。您还可以删除多余的字符串连接:
function addThis(name,logo,status){
$( #follower-Info)。prepend('< div class =row>< div class =col-md-4>< img src ='+ logo +'>< / div>< div class =col-md-4>'+ name +'< / div>< div class =col-md-4>'+ status +'< / div> ;< / DIV>');
}
然后你可以在你的 $中调用它。 getJSON
处理程序:
addThis('Foo','bar.jpg','online') ;
I am currently using a Twitch API that receives information about a specific channel then prepends it to the HTML document. The code that prepends the information is used over and over. I was wondering how exactly do you create a function that could avoid repetition and be called throughout the document?
The codepen can be found here: http://codepen.io/sibraza/pen/AXRRvq
Here is the JQuery Code thats gets used repeatedly:
$("#follower-Info").prepend("<div class ='row'>" + "<div class = 'col-md-4'>" + "<img src='" + logo + "'>" + "</div>" + "<div class='col-md-4'>" + name +"</div>"+ "<div class ='col-md-4'>" + status + "</div></div>")
Would something like this work:
function addThis(){
$("#follower-Info").prepend("<div class ='row'>" + "<div class = 'col-md-4'>" + "<img src='" + logo + "'>" + "</div>" + "<div class='col-md-4'>" + name +"</div>"+ "<div class ='col-md-4'>" + status + "</div></div>")
}
And then I can could call addThis() after each $.getJSON request.
It would work, but you need to pass name
, logo
and status
as parameters to the function. You can also remove the redundant string concatenation:
function addThis(name, logo, status) {
$("#follower-Info").prepend('<div class="row"><div class="col-md-4"><img src="' + logo + '"></div><div class="col-md-4">' + name + '</div><div class="col-md-4">' + status + '</div></div>');
}
Then you can call it from within your $.getJSON
handler:
addThis('Foo', 'bar.jpg', 'online');
这篇关于在JQuery中创建函数以避免再次编写相同的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!