jQuery变量问题

jQuery variable issue

本文关键字:问题 变量 jQuery      更新时间:2023-09-26

快速概述,当用户单击带有锚标记的链接时,它会打开目标页面上离该锚最近的隐藏div。

我的问题似乎很简单,我就是想不明白。

为什么这样做(指定要设置高度的变量,在本例中为high7):

var height7 =  100;
if(window.location.hash) {
      var hash = window.location.hash.substring(1); 
      $('a[name='+hash+']').closest('[id^="option"]').show();
      $('a[name='+hash+']').closest('[id^="option"]').height(height7);
} else {
      // No hash found
}

这不起作用(在这种情况下,试图构建我想要打开的div的名称,将其放在一个变量中并将其传递给height()函数,就像上面一样,由于某种原因,它不接受变量):

if(window.location.hash) {
     var hash = window.location.hash.substring(1); 
     var option_name = $('a[name='+hash+']').closest('[id^="option"]').attr("id");
     var hash_div_height_id = "height" + option_name.substring(6);
     alert(hash_div_height_id);
     $('a[name='+hash+']').closest('[id^="option"]').show();
     $('a[name='+hash+']').closest('[id^="option"]').height(hash_div_height_id);
} else {
      // No hash found
}

您在每种情况下分配不同的值:

$('a[name='+hash+']').closest('[id^="option"]').height(height7); //height = 100
$('a[name='+hash+']').closest('[id^="option"]').height(hash_div_height_id); //height = "height" + option_name.substring(6)

您似乎在分配字符串值

var hash_div_height_id = "height" + option_name.substring(6);
     .height(hash_div_height_id);

这里应该是一个数字

所以hash_div_height_id等于height + something

设置height属性时,它期望

表示像素数的整数,或带附加的可选度量单位(作为字符串)。