ogarich89
@ogarich89
Front-End Developer

Возможно ли сократить код jQuery?

// Сложение и вычитание суммы по клику
	$('.p-btn').click(function(e) {
		e.preventDefault();
		var one = 1;
		var presentValue = $( this ).siblings('input:text').val();
		$( this ).siblings('input:text').val(Number(presentValue) + one);
		var priceValue = $( this ).closest('.basket-row').find('.sum-container span').attr('data-sum');
		priceValue = parseFloat(priceValue);
		var presentPriceValue = $( this ).closest('.basket-row').find('.sum-container span').text();
		presentPriceValue = parseFloat(presentPriceValue);
		$( this ).closest('.basket-row').find('.sum-container span').text(priceValue + presentPriceValue + ' руб.')
	});

	$('.m-btn').click(function(e) {
		e.preventDefault();
		var one = 1;
		var presentValue = $( this ).siblings('input:text').val();
		if (presentValue > 1) {
			$( this ).siblings('input:text').val(Number(presentValue) - one);
			var priceValue = $( this ).closest('.basket-row').find('.sum-container span').attr('data-sum');
			priceValue = parseFloat(priceValue);
			var presentPriceValue = $( this ).closest('.basket-row').find('.sum-container span').text();
			presentPriceValue = parseFloat(presentPriceValue);
			$( this ).closest('.basket-row').find('.sum-container span').text(presentPriceValue - priceValue + ' руб.');
		};
	});


Много повторяющихся строк в коде. Возможно ли вынести некоторые строки в функцию для сокращения записи?
  • Вопрос задан
  • 245 просмотров
Решения вопроса 1
ogarich89
@ogarich89 Автор вопроса
Front-End Developer
var calculateQuantityPrice = function($action, $this) {
		var $siblings = $this.closest('.input-row').find('input:text');
		var $basketSum = $this.closest('.basket-row').find('.sum-container span');
		var presentValue = parseInt($siblings.val());
		var priceValue = parseInt($basketSum.attr('data-sum'));
		var presentPriceValue = parseInt($basketSum.text());

	    if ($action == 'plus') {
	        $siblings.val(presentValue + 1);
	        $basketSum.text(priceValue + presentPriceValue + ' руб.');
	    } else if ($action == 'minus') {
	        $siblings.val(presentValue - 1);
	        $basketSum.text(presentPriceValue - priceValue + ' руб.');
	    }
	};

	$('.p-btn').click(function(e) {
	    e.preventDefault();

	    calculateQuantityPrice('plus', $( this ))
	});

	$('.m-btn').click(function(e) {
	    e.preventDefault();

	    calculateQuantityPrice('minus', $( this ));
	});
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
@vGrabko99
html, css, js, php, golang, mysql
Один уровень абстракции на функцию
Функция должна выполнять только 1 операцию. Она должна выполнять её хорошо. И не чего другого она делать не должна.
Ответ написан
Комментировать
@Inwork277
Ну дак засуньте это всё в функцию и передавайте туда параметр
isPlus == true -> сложение
isPlus == false -> вычитание
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы