2017-08-30 49 views
0

我目前有以下代碼來更新URL。我如何將這個結合成更強大的東西,以便我基本上不重複自己3次。我只希望在更改其中一個字段時更新它。你怎麼聽javascript的多個領域的變化?

$(document).ready(function(){ 
    $('#device_select').change(function() { 
     var device = $(this).val(); 
     var face = $('#face_select').val(); 
     var position = $('#position_select').val(); 
     document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
    }); 
    $('#face_select').change(function() { 
     var device = $('#device_select').val(); 
     var face = $(this).val(); 
     var position = $('#position_select').val(); 
     document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
    }); 
    $('#position_select').change(function() { 
     var device = $('#device_select').val(); 
     var face = $('#face_select').val(); 
     var position = $(this).val(); 
     document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
    }); 
}); 

回答

1

爲什麼不把你的代碼封裝在函數中?

function updateURL() { 
    var device = $('#device_select').val(); 
    var face = $('#face_select').val(); 
    var position = $('#position_select').val(); 
    document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
} 

然後你可以打電話給你想要的功能隨時隨地:

$(document).ready(function(){ 
    $('#device_select').change(updateURL); 
    $('#face_select').change(updateURL); 
    $('#position_select').change(updateURL); 
}); 

更妙的是,你可以添加第二個功能,使你的代碼更易讀:

function listenForChanges(){ 
    $('#device_select').change(updateURL); 
    $('#face_select').change(updateURL); 
    $('#position_select').change(updateURL); 
} 

並稱之爲功能上document.ready

$(document).ready(listenForChanges); 
+0

完美爲我的scenerio。謝謝! – csling

1

這種方法怎麼樣?

$(document).ready(function(){ 
     ['#position_select', '#device_select', '#face_select'].forEach(
      function(ev){ 
       $(ev).change(function() { 
        var device = $('#device_select').val(); 
        var face = $('#face_select').val(); 
        var position = $('#position_select').val(); 
        document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
       }); 
      } 
     ) 
    } 
    ) 
4
$('#position_select, #device_select, #face_select').change(function() { 
     var device = $('#device_select').val(); 
     var face = $('#face_select').val(); 
     var position = $('#position_select').val(); 
     document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position; 
    }); 

你試過somethign這樣嗎?