You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

当输入数的GCD为1时隐藏span标签的问题(附代码)

解决分数简化时无法隐藏对应span标签的问题

我来帮你搞定这个隐藏span的问题!你的核心bug出在reduce函数里的$(this)指向错误——当你直接用reduce(1,5)这种方式调用函数时,函数内部的this并没有绑定到你想要操作的DOM元素上(此时this指向的是全局window对象),所以找不到对应的.SimplificationPrompt父元素,自然没法触发隐藏操作。

解决方案:明确绑定函数的操作目标

我们可以调整reduce函数的设计,让它能明确知道要操作哪个DOM元素,这里提供两种简单的实现方式:

方式1:给reduce函数添加元素参数

直接把要填充结果的DOM元素作为参数传递给函数,这样就能精准操作对应的父容器:

$(document).ready(function () { 
  function reduce(numerator, denominator, targetElement){ 
    var gcd = function gcd(a,b){ 
      return b ? gcd(b, a%b) : a; 
    }; 
    gcd = gcd(numerator,denominator); 

    if ((denominator/gcd) == 1) { 
      return [numerator/gcd]; 
    } else { 
      if(gcd === 1){ 
        // 现在能精准找到要隐藏的父容器了
        $(targetElement).parent(".SimplificationPrompt").hide(); 
        return [numerator/gcd +"|"+ denominator/gcd]; 
      }else{ 
        return [numerator/gcd +"|"+ denominator/gcd]; 
      } 
    } 
  } 

  // 调用时传递对应的DOM元素
  var reducefraction = reduce(4,12, $('.reducefraction')); 
  $('.reducefraction').html(reducefraction ); 

  var reducefraction2 = reduce(1,5, $('.reducefraction2')); 
  $('.reducefraction2').html(reducefraction2 ); 
}); 

方式2:用call绑定this指向

如果你不想修改函数参数,可以用Function.prototype.call来强制绑定this为目标DOM元素:

$(document).ready(function () { 
  function reduce(numerator,denominator){ 
    var $target = $(this); // 现在this是我们绑定的DOM元素
    var gcd = function gcd(a,b){ 
      return b ? gcd(b, a%b) : a; 
    }; 
    gcd = gcd(numerator,denominator); 

    if ((denominator/gcd) == 1) { 
      return [numerator/gcd]; 
    } else { 
      if(gcd === 1){ 
        $target.parent(".SimplificationPrompt").hide(); 
        return [numerator/gcd +"|"+ denominator/gcd]; 
      }else{ 
        return [numerator/gcd +"|"+ denominator/gcd]; 
      } 
    } 
  } 

  // 用call绑定this为对应的DOM元素
  var reducefraction = reduce.call($('.reducefraction')[0], 4,12); 
  $('.reducefraction').html(reducefraction ); 

  var reducefraction2 = reduce.call($('.reducefraction2')[0], 1,5); 
  $('.reducefraction2').html(reducefraction2 ); 
}); 

对应的HTML代码(无需修改)

<b>This should be hidden</b>: <span class="SimplificationPrompt"><span class="reducefraction"></span></span> <br>
This shouldn't be hidden: <span class="SimplificationPrompt"><span class="reducefraction2"></span></span>

现在运行代码后,当分数无法简化(gcd=1)时,对应的.SimplificationPrompt标签就会被正确隐藏啦!

内容的提问来源于stack exchange,提问作者Snoops

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:00:33