如果可能,請尋求幫助。將Jquery代碼重構爲重用函數
我已經創造了一些jQuery代碼,沒有工作,但我覺得有點cluncky,想正確地重構它...
在代碼由用戶響應點擊的那一刻,它會檢查服務器是否允許用戶投票,如果有的話,它會通過ajax處理投票,並相應地移動投票。
然而,目前成立僅被點擊了「投了」鏈接時,它增加了一個表決計數運行。當用戶點擊class =「vote down」的鏈接時,我還想做的是從投票計數中減去1,但是我不想重複相同的代碼,因爲這一點。
想知道是否有反正打包所有的代碼放到一個函數,並說:「加一個,如果被點擊投票了,堂堂一個,如果不合理點擊。
非常感謝
<a href="link class="vote up"> Vote Up </a>
<a href="link class="vote down"> Vote Down</a>
$('body#true .voteUp').click(function(){
// Get the song meaning
$thisLink = $(this);
var idSm = $(this).parents("div:eq(1)").attr("id");
//Validate that user isnt rating their own song meaning
$.getJSON('http://localhost:8500/mxRestore/model/mdl_songs.cfc?method=getRateSm&returnFormat=json&queryformat=column',
{idSm: idSm},
function(data){
var bVoteAllowed = data.ROWCOUNT < 1;
if(bVoteAllowed){
// User can vote
$.getJSON('http://localhost:8500/mxRestore/model/mdl_songService.cfc?method=rateSm&returnFormat=json&queryformat=column',
{idSm:idSm,action:true})
// Change vote accordingly
var totalQuantity = 0;
var quantity = $thisLink.parent().parent().children('.rateValue').text();
quantity = parseInt(quantity);
totalQuantity = quantity + 1;
$thisLink.parent().parent().children('.rateValue').text(String(totalQuantity)).effect("highlight", {}, 3000);
}else {
$thisLink.text("you are not allowed to vote")
}
})
return false
})
'體#TRUE'是不必要的,可以慢下來。只需使用'#true'。更好的是,我會這樣寫'#true a.voteUp' – 2009-12-10 20:37:04
感謝您的建議......爲什麼這是一種改進的方法?謝謝 – namtax 2009-12-10 22:09:31