我想动态更改字体,但是我的代码仅在我第一次更改字体时表现良好。似乎我的代码会记住以前单击的按钮,并在每次我为按钮选择新字体时添加要更改的按钮。我的代码位于jsfiddle



function font(id,element){
  $(id).bind('change',function(){
    var fontTypeSelected = $(id).val();
    $(element).css('font-family',fontTypeSelected);
  });
}

$('#settings-ID').change(function(){
  font('#font','#' + $('#settings-ID').val());
});

$('.list').on('click','.settings',function(){
  // Set current row or box section ID
  $('#settings-ID').val($(this).attr('id'));
  $("#settings-ID").trigger("change");
});

.list div {
  float:left;
  padding:10px;
  background-color:#CCC;
  margin:10px 10px 0 0;
  cursor:pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on one of the buttons below to change font
<div class="list">
  <div class="settings" id="1">Font one</div>
  <div class="settings" id="2">Font two</div>
</div>
<br>Selected button ID: <input type="text" id="settings-ID" placeholder="None selected"><br>
<br>
<select class="form-control" id="font">
  <option>Arial</option>
  <option>Courier</option>
  <option>Verdana</option>
  <option>Times new roman</option>
</select>





我真的希望有人可以帮助我解决这个问题。我有点卡在这里。

最佳答案

调用函数时,您正在定义多个更改事件

在定义下一个事件之前,使用.unbind("change")删除更改事件。

function font(id,element){
  $(id).unbind('change').bind('change',function(){
    var fontTypeSelected = $(id).val();
    $(element).css('font-family',fontTypeSelected);
  });
}

关于javascript - 通过JQuery .change重新加载javascript函数会添加以前运行的变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41899651/

10-11 02:37