2016-08-01 64 views
0

好吧,所以這就是我在當前... 基本上我追加到基於窗口寬度的URL的結尾(使用drawNewUrl()很好地工作)。jQuery - 窗口大小調整事件 - 從URL添加和刪除變量

在窗口調整大小頁面重新加載應該刪除附加屬性我添加在URL('?url/suffix/example /')末尾。但是,它並沒有刪除urlAppend(與jQuery (urlAppend).remove();),它不斷地將urlAppend添加到窗口調整大小的URL的末尾。 (即:example.com/?url/suffix/example/1/?url/suffix/example/1/)。我將如何刪除urlAppend調整大小,並允許繪製新的url?

var urlAppend; 

function drawNewUrl() { 
    if (jQuery(window).width() > 1200) { 
     var urlAppend = '?url/suffix/example/3/'; 
    } else if (jQuery(window).width() > 768) { 
     var urlAppend = '??url/suffix/example/2/'; 
    } else { 
     var urlAppend = '?url/suffix/example/1/'; 
    } 

    jQuery('.class').attr('href', function() { 
     return this.href + urlAppend; 
    }); 
} 
jQuery(window).resize(function() { 
    jQuery(urlAppend).remove(); 
    drawNewUrl(); 
}); 
jQuery(document).ready(function() { 
    drawNewUrl(); // for onload 
}); 
+0

'urlAppend = '''而不是'的jQuery(urlAppend)卸下襬臂()'? – kasperite

+0

@kasperite Hmmmm ...這將無法用於從url中刪除屬性..僅用於重置變量 –

回答

0

試試我的解決辦法,看看它是否適合你。我正在使用正則表達式有條件地將urlAppend添加到href屬性。

var urlAppend; 
 

 
function drawNewUrl() { 
 
    if (jQuery(window).width() > 1200) { 
 
     var urlAppend = '?url/suffix/example/3/'; 
 
    } else if (jQuery(window).width() > 768) { 
 
     var urlAppend = '?url/suffix/example/2/'; 
 
    } else { 
 
     var urlAppend = '?url/suffix/example/1/'; 
 
    } 
 

 
    jQuery('.class').attr('href', function() { 
 
    \t return this.href.replace(/(\?url\/suffix\/example\/\d\/)?$/i, urlAppend); 
 
    }); 
 
} 
 
jQuery(window).resize(function() { 
 
    drawNewUrl(); 
 
}); 
 
jQuery(document).ready(function() { 
 
    drawNewUrl(); // for onload 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<a href="#" class="class"> 
 
    Link 1 
 
</a> 
 
<a href="#" class="class"> 
 
    Link 2 
 
</a> 
 
<a href="#" class="class"> 
 
    Link 3 
 
</a> 
 
<a href="#" class="class"> 
 
    Link 4 
 
</a>

0

我會做這樣的,工作小提琴:https://jsfiddle.net/s22su/6wxmrebu/1/

var defaultUrl = 'hello.php'; 

function drawNewUrl() { 
    var urlAppend = ''; 
    var w = jQuery(window).width(); 
    console.log('Width: ', w); 
    switch(w) { 
    case 1200: 
     var urlAppend = '?url/suffix/example/3/'; 
     break; 
    case 768: 
     var urlAppend = '?url/suffix/example/2/'; 
     break; 
    default: 
     var urlAppend = '?url/suffix/example/1/'; 
    } 

    var fullUrl = defaultUrl + urlAppend; 
    jQuery('.class').attr('href', fullUrl); 
} 
jQuery(window).resize(function() { 
    drawNewUrl(); 
}); 
jQuery(document).ready(function() { 
    drawNewUrl(); // for onload 
});