我对Jquery和Javascript很新,但我创建了一个与symfony2中的php控制器通信的脚本。
我的问题是,我该怎么做才能减少脚本长度 - >也许有一种更聪明的方法来解决我用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);
}
});
}
});
});
答案 0 :(得分:2)
您可以使用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);
}
}
);
}
});
});
一些一般性的想法: