V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
ling516
V2EX  ›  JavaScript

js 代码函数传参的时候要把单引号一起传入怎么处理

  •  
  •   ling516 · 2022-03-06 01:40:11 +08:00 · 1930 次点击
    这是一个创建于 754 天前的主题,其中的信息可能已经有所发展或是发生改变。

    原代码,查找所有选择器,并根据文本选中元素并点击

    Array.from(document.querySelectorAll('.class'))
           .find(el => el.textContent === '1')
           .click();
    

    想写成函数复用,发现传参的时候单引号必须在函数中才行 请问如何解决 谢谢

    function findSelectorTextClick(selector, text) {
        Array.from(document.querySelectorAll(selector))
            .find(el => el.textContent === Text)
            .click();
    }
    
    findSelectorTextClick('.class', '1')
    
    9 条回复    2022-03-06 14:54:44 +08:00
    wudicgi
        1
    wudicgi  
       2022-03-06 02:08:44 +08:00   ❤️ 1
    不是 text 变量大小写搞错了?
    ling516
        2
    ling516  
    OP
       2022-03-06 02:12:15 +08:00
    @wudicgi text 变量是 1
    ysc3839
        3
    ysc3839  
       2022-03-06 02:16:08 +08:00 via Android
    “单引号必须在函数中才行”具体指的是什么?
    MossFox
        4
    MossFox  
       2022-03-06 02:17:47 +08:00
    如果用的是 VS Code ,编辑器第一行加个 // @ts-check

    有提示。
    KobeSama
        5
    KobeSama  
       2022-03-06 05:52:48 +08:00
    "'1'"|| '\'1\''
    `'1'` || `'${text}'`
    ragnaroks
        6
    ragnaroks  
       2022-03-06 09:41:23 +08:00
    #1 正解

    function findSelectorTextClick(selector, text) {
    Array.from(document.querySelectorAll(selector))
    .find(el => el.textContent === text)
    .click();
    }

    findSelectorTextClick('.tag', ' 传参')
    ling516
        7
    ling516  
    OP
       2022-03-06 12:21:37 +08:00
    @wudicgi 谢谢
    ling516
        8
    ling516  
    OP
       2022-03-06 12:21:49 +08:00
    @ragnaroks 谢谢 犯低级错误了
    ljsh093
        9
    ljsh093  
       2022-03-06 14:54:44 +08:00 via iPhone
    用``可以随便传
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2832 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:53 · PVG 22:53 · LAX 07:53 · JFK 10:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.