首页 > 解决方案 > 为什么 .val('') 去掉单引号

问题描述

我有以下 jQuery 代码,

$(document).ready(function() {
  $("#results").on('click', 'input:checkbox', function() {
    // in the handler, 'this' refers to the box clicked on
    var $box = $(this);
    if ($box.is(":checked")) {
      // the name of the box is retrieved using the .attr() method
      // as it is assumed and expected to be immutable
      var group = "input:checkbox[name='" + $box.attr("name") + "']";
      // the checked state of the group/box on the other hand will change
      // and the current value is retrieved using .prop() method
      $(group).prop("checked", false);
      $box.prop("checked", true);
      $('#wp_theme_url').val($(this).val());
      $('#wp_theme_slug').val($(this).data("themeslug"));
    } else {
      $box.prop("checked", false);
      $('#wp_theme_url').val('');
      $('#wp_theme_slug').val('');
    } 
  });
});

但是,如果我取消选择一个复选框,它会从 value 属性中删除 ='' 导致

<input ... value>

代替

<input ... value=''>

任何想法为什么?

标签: javascriptjquery

解决方案


value 属性仅包含默认值,而不包含实际的实时值。


推荐阅读