[英]Shorten function in Javascript / Jquery
LF way to short my js/jquery function: LF缩短我的js / jquery函数的方法:
$.ajax({ // Start ajax post
..........
success: function (data) { // on Success statment start
..........
//1. Part
$('var#address').text(data.address);
$('var#telephone').text(data.telephone);
$('var#mobile').text(data.mobile);
$('var#fax').text(data.fax);
$('var#email').text(data.email);
$('var#webpage').text(data.webpage);
//2. Part
if (!data.address){ $('p#address').hide(); } else { $('p#address').show(); };
if (!data.telephone){ $('p#telephone').hide(); } else { $('p#telephone').show(); };
if (!data.mobile){ $('p#mobile').hide(); } else { $('p#mobile').show(); };
if (!data.fax){ $('p#fax').hide(); } else { $('p#fax').show(); };
if (!data.email){ $('p#email').hide(); } else { $('p#email').show(); };
if (!data.webpage){ $('p#webpage').hide(); } else { $('p#webpage').show(); };
}, End Ajax post success statement
Here is my html: 这是我的html:
<p id="address">Address:<var id="address">Test Street 999 2324233</var></p>
<p id="telephone">Telephone:<var id="telephone">+1 0000009</var></p>
<p id="mobile">Mobile:<var id="mobile">+1 0000009</var></p>
<p id="email">E-mail:<var id="email">info@example</var></p>
<p id="webpage">Web Page:<var id="webpage">www.example.com</var>/p>
How can we reduce the number of selector* (1. part) * and else if the amount (2. part) ? 我们如何减少选择器* (1. part) *的数量,否则减少选择器(2. part)的数量?
Assuming your object's property names exactly match the spelling of your element ids you can do this: 假设对象的属性名称与元素ID的拼写完全匹配,则可以执行以下操作:
for (var k in data) {
$('var#' + k).text(data[k]);
$('p#' + k).toggle(!!data[k]);
}
...because .toggle()
accepts a boolean to say whether to show or hide. ...因为.toggle()
接受布尔值来表示是显示还是隐藏。 Any properties that don't have a matching element id would have no effect. 没有匹配的元素ID的任何属性都将无效。
Note: your html is invalid if you have multiple elements with the same ids, but it will still work because your selectors specify the tag and id. 注意:如果您有多个具有相同ID的元素,则html无效,但由于选择器指定了标记和ID,因此html仍然有效。 Still, it might be tidier to just remove the ids from the var elements: 不过,仅从var元素中删除ID可能会更整洁:
<p id="address">Address:<var>Test Street 999 2324233</var></p>
<!-- etc. -->
With this JS: 有了这个JS:
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
And then adding some code to hide any elements that aren't in the returned data
object: 然后添加一些代码以隐藏返回的data
对象中没有的任何元素:
$('var').parent('p').hide();
...and putting it all together: ...并将它们放在一起:
$.ajax({
// other ajax params here
success : function(data) {
$('var').parent('p').hide();
for (var k in data) {
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
}
}
});
Demo: http://jsfiddle.net/z98cw/1/ 演示: http : //jsfiddle.net/z98cw/1/
As long as the properties of the object match the id
attributes of the p
tags you can iterate through the object using the property name as a selector. 只要对象的属性与p
标记的id
属性匹配,就可以使用属性名称作为选择器来遍历对象。 Also since id
attributes are unique, refrain from prefixing the selector with var
it is unnecessary. 同样,由于id
属性是唯一的,因此不要在选择器前加上var
前缀,这是不必要的。
var data = {
address: "address",
telephone: "telephone",
mobile: "mobile",
fax: "fax",
email: "email",
webpage: "webpage"
};
for(x in data){
var elem = $("#" + x);
if(elem.length == 1){
elem.text(data[x]);
}
}
JS Fiddle: http://jsfiddle.net/3uhx6/ JS小提琴: http : //jsfiddle.net/3uhx6/
["address", "telephone", "mobile", "fax", "email", "webpage"].map(
function(key) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show();
} else {
$('p#' + key).hide();
}
});
But you should not. 但是你不应该。
This is what templating systems are created for. 这就是创建模板系统的目的。 If you insist on using jQuery there is a jQuery plugin: https://github.com/codepb/jquery-template 如果您坚持使用jQuery,则有一个jQuery插件: https : //github.com/codepb/jquery-template
More: What Javascript Template Engines you recommend? 更多: 您推荐什么Javascript模板引擎?
I would use javascript templates for this (I've shortened the example a quite a bit, but you should get the gist). 我将为此使用javascript模板(我将示例简化了很多,但是您应该明白要点)。
First the template, I love Underscore.js for this so I gonna go ahead and use that. 首先,模板是我喜欢Underscore.js的模板,因此我将继续使用它。
<% if data.address %>
<p id="address">Address: {%= Test Street 999 2324233 %}</p>
to compile this inside your success
function 在您的success
函数中进行编译
success: function(data) {
//assuming data is a json that looks like this {'address':'my street'}
var template = _.template(path_to_your_template, data);
$('var#addresscontainer').html(template);
}
Thanks for birukaze and nnnnnn : 感谢birukaze和nnnnnn :
With your advice came function;) : 根据您的建议提供了功能;):
for (var key in data) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show().find('var').text(data[key]);
} else {
$('p#' + key).hide();
}
};
Now i can avoid for selector with var. 现在我可以避免使用var选择器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.