我对 Jquery 和 Javascript 很陌生,但我创建了一个与 symfony2 中的 php Controller 通信的脚本。
我的问题是,我能做些什么来减少脚本长度 --> 也许有一种更聪明的方法来解决我用 switch 表达式解决的逻辑?
谢谢
/**
* This function gets the current clicked buttons value and post it to the given action + returns the correct value
*/
$(document).ready(function() {
$('button.rating-button').click(function(event) {
event.preventDefault();
var $element = $(this).attr('id');
var $rating = $(this).attr('value');
var $messageId = $(this).closest('ul').next('input:hidden').val();
if(typeof $rating !== 'undefined' && $rating != null) {
$.post(Routing.generate('rating_vote', { 'messageId': $messageId, 'ratingCode': $rating }),
function($json) {
$('button#'+$element).parent().find('span').text($json.numberOfRatings);
/* check if oldRating is defined and oldRating is not the same as new rating ( prevent decrease of actual value if this is the first vote entry for the current message and the specific user ) */
if(typeof $json.oldRating !== 'undefined' && $json.oldRating != null && ($json.oldRating != $rating) ) {
switch($json.oldRating) {
case 1:
$oldElement = 'rating-first';
break
case 2:
$oldElement = 'rating-second';
break;
case 3:
$oldElement = 'rating-third';
break;
}
$('button#'+$oldElement).parent().find('span').text(Number($('button#'+$oldElement).parent().find('span').text()) -1);
}
});
}
});
});
最佳答案
您可以将 switch case 逻辑替换为 this rather neat concept .
$(function() {
$('button.rating-button').on('click',function(event) {
event.preventDefault();
var $this = $(this),
element = $this.attr('id'),
rating = $this.attr('value'),
messageId = $this.closest('ul').next('input:hidden').val();
if(typeof rating !== 'undefined' && rating != null) {
$.post(Routing.generate('rating_vote', { 'messageId': messageId, 'ratingCode': rating }),
function(json) {
$('button#'+element).parent().find('span').text(json.numberOfRatings);
if(typeof json.oldRating !== 'undefined' && json.oldRating != null && (json.oldRating != rating) ) {
var oldElement = ({
1: 'rating-first',
2: 'rating-second',
3: 'rating-third'
})[json.oldRating];
$('button#'+oldElement).parent().find('span').text(Number($('button#'+oldElement).parent().find('span').text()) -1);
}
}
);
}
});
});
一些总体想法:
- 使用 jQuery 时,使用 $[varname] 作为包含 jQuery 对象的变量的指示符(了解您的 php 背景,一开始可能会感觉很奇怪)
- 创建 jQuery 对象对性能来说有点沉重,因此最好确保只创建一次
关于javascript - 如何减少这个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14584813/