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

如何正确判断字符串不等于指定值?以ev.target.id !== "dragPos"为例

正确判断ev.target.id不等于"dragPos"的方法

Hey there! Let's work through this properly. First, let's fix the syntax issue in your original code snippet, then cover the actual comparison logic and edge cases you might want to account for.

1. Fix the Syntax Error First

Your original code has mismatched parentheses that will break execution:

if((... && ev.target.id !== "dragPos"){

Notice the extra opening parenthesis ( before the ... and a missing closing parenthesis for the if condition. The corrected basic structure should look like one of these:

// If your preceding condition doesn't need extra parentheses for clarity
if (... && ev.target.id !== "dragPos") {
  // Your logic here
}

// Or if you want to wrap the preceding condition in parentheses
if ((yourPrecedingCondition) && ev.target.id !== "dragPos") {
  // Your logic here
}

2. The Core Comparison: !== is Correct (But Watch Edge Cases)

Using !== "dragPos" is the right approach here—it’s the strict inequality operator, which checks both value and type, avoiding unexpected matches from type coercion (like != would allow). However, there are a couple of edge cases to keep in mind:

  • Case 1: ev.target might be null or undefined
    If there’s a scenario where ev.target could be null (e.g., the event is triggered on an element that gets removed from the DOM), accessing .id directly will throw an error. Use optional chaining to safely handle this:

    if (... && ev.target?.id !== "dragPos") {
      // This skips the id check entirely if ev.target is null/undefined
    }
    
  • Case 2: The element has no id attribute
    If ev.target exists but has no id, ev.target.id will be an empty string "". "" !== "dragPos" evaluates to true, which is probably what you want—but if you need to explicitly exclude elements without an id, add an extra check:

    if (... && ev.target.id && ev.target.id !== "dragPos") {
      // Only runs if the element has an id AND it's not "dragPos"
    }
    

3. Quick Confirmation

Just to be clear: !== is exactly the operator you need for this strict inequality check. It ensures you won’t accidentally match values that are coerced to the same type (like a number 0 matching the string "0" with !=). Stick with it for reliable results.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:43:12