巷子口的你

文章 评论 浏览 29

巷子口的你 2025-02-20 18:51:15

您可以使用 luxon 库ISO日期字符串。

然后,可以在几分钟内获得UTC偏移,如果是0,我们在UTC(或GMT)中,

我将所有这些都包装在必需的 iSUTC()函数中。

let { DateTime } = luxon;

let inputs = [
    '2020-01-01T00:00:00Z',
    '2020-01-01T00:00:00+00',
    '2020-01-01T00:00:00+0000',
    '2020-01-01T00:00:00+00:00',
    '2020-01-01T00:00:00+01',
    '2020-01-01T00:00:00+0100',
    '2020-01-01T00:00:00+01:00'
];


function isUTC(input) {
    const dt = DateTime.fromISO(input, { setZone: true })
    return dt.offset === 0;
}

console.log('Input'.padEnd(30), 'isUTC');
for(let input of inputs) {
    console.log(input.padEnd(30), isUTC(input));
}
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

can 也可以使用正则态度来执行此操作:

let inputs = [
    '2020-01-01T00:00:00Z',
    '2020-01-01T00:00:00+00',
    '2020-01-01T00:00:00+0000',
    '2020-01-01T00:00:00+00:00',
    '2020-01-01T00:00:00+01',
    '2020-01-01T00:00:00+0100',
    '2020-01-01T00:00:00+01:00'
];


function isUTC(input) {
    return getUTCOffsetMinutes(input) === 0;
}

function getUTCOffsetMinutes(isoDate) {
    // The pattern will be ±[hh]:[mm], ±[hh][mm], or ±[hh], or 'Z'
    const offsetPattern = /([+-]\d{2}|Z):?(\d{2})?\s*$/;
    if (!offsetPattern.test(isoDate)) {
        throw new Error("Cannot parse UTC offset.")
    }
    const result = offsetPattern.exec(isoDate);
    return (+result[1] || 0) * 60 + (+result[2] || 0);
}

console.log('Input'.padEnd(30), 'isUTC');
for(let input of inputs) {
    console.log(input.padEnd(30), isUTC(input));
}
.as-console-wrapper { max-height: 100% !important; }

You can use the luxon library to parse ISO date strings.

One can then get the UTC offset in minutes, if this is 0 we're in UTC (or GMT)

I've wrapped this all up in the required isUTC() function.

let { DateTime } = luxon;

let inputs = [
    '2020-01-01T00:00:00Z',
    '2020-01-01T00:00:00+00',
    '2020-01-01T00:00:00+0000',
    '2020-01-01T00:00:00+00:00',
    '2020-01-01T00:00:00+01',
    '2020-01-01T00:00:00+0100',
    '2020-01-01T00:00:00+01:00'
];


function isUTC(input) {
    const dt = DateTime.fromISO(input, { setZone: true })
    return dt.offset === 0;
}

console.log('Input'.padEnd(30), 'isUTC');
for(let input of inputs) {
    console.log(input.padEnd(30), isUTC(input));
}
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

You can do this with RegEx too:

let inputs = [
    '2020-01-01T00:00:00Z',
    '2020-01-01T00:00:00+00',
    '2020-01-01T00:00:00+0000',
    '2020-01-01T00:00:00+00:00',
    '2020-01-01T00:00:00+01',
    '2020-01-01T00:00:00+0100',
    '2020-01-01T00:00:00+01:00'
];


function isUTC(input) {
    return getUTCOffsetMinutes(input) === 0;
}

function getUTCOffsetMinutes(isoDate) {
    // The pattern will be ±[hh]:[mm], ±[hh][mm], or ±[hh], or 'Z'
    const offsetPattern = /([+-]\d{2}|Z):?(\d{2})?\s*$/;
    if (!offsetPattern.test(isoDate)) {
        throw new Error("Cannot parse UTC offset.")
    }
    const result = offsetPattern.exec(isoDate);
    return (+result[1] || 0) * 60 + (+result[2] || 0);
}

console.log('Input'.padEnd(30), 'isUTC');
for(let input of inputs) {
    console.log(input.padEnd(30), isUTC(input));
}
.as-console-wrapper { max-height: 100% !important; }

检查ISO 8601字符串是否在UTC中

巷子口的你 2025-02-20 16:01:24

这是较旧的PostgreSQL版本和Prisma的已知错误。

https://github.com/prisma/prisma/prisma/prisma/issues/7251

版本12或更高版本应解决此错误。另外,您可以创建单个迁移文件,其唯一目的是更新枚举。

This is a known bug with older PostgreSQL versions and Prisma.

https://github.com/prisma/prisma/issues/7251

Upgrading to PostgreSQL version 12 or higher should resolve this error. Alternatively, you can create single migration files whose only purpose is to update the enum.

在Prisma中的现有枚举类型中添加新价值

巷子口的你 2025-02-20 15:34:47

将日期保留为简单的日期字符串(2022-01-31)会导致JS中的数据丢失,并将其提供到日期构造函数可能会导致错误的日期。检查此 SO问题 for for for for for for for for for。

通常,我将日期转换为 iso格式,通过使用 date.toisstring 。接下来,当我想将其解析为JS日期对象时,我使用 parseiso 的方法date-fns

这是一个codesandbox示例:

Keeping date as simple date string(2022-01-31) causes data loss in JS and providing it to Date constructor can result in wrong date. Check this SO question for more.

Generally I convert my date to ISO format by using Date.toISOString. Next when I want to parse it as JS Date object, I use parseISO method of date-fns.

Here is a CodeSandbox example: https://codesandbox.io/s/summer-bush-iv0h2g?file=/src/index.js

JS-使用TimeZone不正确转换的时间从本地转换为UTC

巷子口的你 2025-02-20 14:15:21

您需要将您的应用程序urls.py包含在您的项目urls.py中:

from django.urls import path, include

urlpatterns = [
  path("", include("your_app.urls")),
]

You need to include your app urls.py into your project urls.py like this:

from django.urls import path, include

urlpatterns = [
  path("", include("your_app.urls")),
]

我无法链接Django中的页面,我的代码正确。我需要做什么?

巷子口的你 2025-02-20 12:50:06

查看该 uninstall.sh ,有一个 homebrew_prefix_default 根据处理器类型设置的位置,并且有用法信息说:

-p, --path=PATH  Sets Homebrew prefix. Defaults to ${homebrew_prefix_default}.

因此,您肯定可以覆盖您可以覆盖通过 - 路径= ... 选项,默认位置与您想要的路径,即脚本将为Intel机器选择的路径,即/usr/local

Looking at that uninstall.sh, there's a spot where homebrew_prefix_default gets set according to the processor type, and there's usage info that says:

-p, --path=PATH  Sets Homebrew prefix. Defaults to ${homebrew_prefix_default}.

So it sure looks like you can override the default location by passing the --path=... option with the path that you want, namely the one that the script would've chosen for an Intel machine, i.e /usr/local.

我可以在macos苹果硅上卸载啤酒

巷子口的你 2025-02-20 06:29:27
this.localize.changeLanguage(lng) here what you doing that might be affecting changing the route

如果您使用NGX-Translate,则可以通过以下方法更改语言,

如果您想更改路由以及查看此解决方案
angular2-带语言的路线

constructor(private translate: TranslateService) {
    translate.setDefaultLang('en'); // default language (in app.component)
  }
  
  useLanguage(language: string) {
    this.translate.use(language);
  }
this.localize.changeLanguage(lng) here what you doing that might be affecting changing the route

if you using ngx-translate you can change the language just by using the below method

if you want to change the route as well checkout out this solution
Angular2 - route with language

constructor(private translate: TranslateService) {
    translate.setDefaultLang('en'); // default language (in app.component)
  }
  
  useLanguage(language: string) {
    this.translate.use(language);
  }

当更改语言时,路线正在附加到,而不仅仅是用选定的语言更改

巷子口的你 2025-02-20 05:01:37

否。redistimeseries当前是(v1.x)单列时间序列数据库,这意味着一个时间序列是一组(时间戳,值)对。您正在询问多列(或多尺寸)功能。

但是,通过创建多个时间序列,您不会失去任何功能。您可以获得简单性,并更好地处理缺失值。由于有效压缩,所需的额外内存是最小值,并使用标签作为辅助索引,您可以轻松地从多个时间序列查询数据。

No. RedisTimeSeries is currently (v1.X) a single-column time series database, which means that a time series is a set of (timestamp, value) pairs. You are asking about multi-column (or multi-metric) capability.

Nevertheless, by creating multiple time series you are not loosing any capabilities. You gain simplicity and also better flexibility for handling missing values. Due to the efficient compression, the extra memory required is minimal, and using labels as secondary indexes you can easily query data from multiple time series.

REDIS时间 - 表示数值值为值列表

巷子口的你 2025-02-19 22:49:30

您的查询

select * from taxiService.operatoragentsauditlog
where hourOfYear =3655
  and actionType ='XYZ'
  and operatorId in ('100','200') limit 500;

将查看 ActionType operatorId 索引以查找与该列上限制匹配的所有行,而不是需要遍历所有候选行以检查是否符合它们还与另外两个限制相匹配。这就是为什么您需要允许过滤。从理论上讲, actionType ='xyz'可能与一百万行相匹配,因此此查询需要超过一百万行才能返回少数匹配所有candiate行。

一些搜索引擎具有与两个索引查找相交的有效方法 - 也许 actionType ='xyz'具有一百万个匹配项,并且 operatorId在('100',''200') in('100','200')中有一百万场比赛,但他们的交叉点只有10行。搜索引擎使用跳过列表机制来有效地计算交叉点。但是Scylla没有此功能。它只会选择两个索引之一(您不知道哪个索引),然后一一审视其匹配项。顺便说一句,请注意,即使Scylla确实支持有效的索引交叉点,您的 hourofyear = 3655 限制也没有索引,因此无论如何都需要逐行过滤。

正如亚伦(Aaron正在使用索引),或 - 将表格架构更改为更好地匹配查询的东西。在许多情况下,后者总是很好的建议。

关于Nohostavailable Exception-这意味着Scylla副本由于某种原因未能执行此查询。它可能表明一个错误或超时(这也是一个错误,因为像您的查询这样的扫描应该进行分页 - 不要超时)。如果在此请求时出现错误消息,请查看Scylla日志,并在Scylla Bug Tracker中报告问题,请 https://github.com/scylladb/scylla/issues

Your query

select * from taxiService.operatoragentsauditlog
where hourOfYear =3655
  and actionType ='XYZ'
  and operatorId in ('100','200') limit 500;

Will look at either the actionType or operatorId index to find all the rows matching the restriction on that column, and than need to go over all the candidate rows to check if they also match the two other restrictions. That's why you need ALLOW FILTERING. Theoretically, actionType = 'XYZ' may match a million rows, so this query will need to go over a million rows just to return a handful that match all the candiate rows.

Some search engines have an efficient way to intersect two index lookups - maybe actionType = 'XYZ' has a million matches, and operatorId in ('100', '200') has a million matches, but their intersection is just 10 rows. Search engines use a skip list mechanism to allow the intersection to be calculated efficiently. But Scylla doesn't have this feature. It will pick just one of the two indexes (you don't know which), and go over its matches one by one. By the way, please note that even if Scylla did support efficient index intersection, your hourOfYear = 3655 restriction isn't indexed, so would need row-by-row filtering anyway.

As Aaron noted in his answer, the solution can be to use ALLOW FILTERING if the one index match results in a small-enough number of matches (it would be better to have just one index, not two, so you'll know exactly which index is being used), or - change your table schema to something which better matches your queries. The latter is always good advice in many situations.

Regarding the NoHostAvailableException - it means the Scylla replicas failed to perform this query for some reason. It might indicate a bug, or a timeout (which would also be a bug, because a scan like your query should do paging - not time out). Please look at the Scylla log if there's an error message that appears at the time of this request, and report the problem in the Scylla bug tracker at https://github.com/scylladb/scylla/issues.

在Scylla DB中,如何查询记录是否有多种条件而不提及允许过滤?

巷子口的你 2025-02-19 17:56:41

使用 InnerHtml 或在您的情况下 insertadjacenthtml &lt; script&gt; 标记添加到文档中不起作用,因为历史上试图防止潜在的交叉浏览器站点脚本攻击( https://www.w3.org/tr/2008/wd-html5-20080610/dom.html#innerhtml0
您能做的就是这样的事情:

const s = document.createElement("script");
s.type = "module";
s.innerText = `import './components/nav-bar.js'`;
this.append(s);
// or simply directly without the script: `import('./comp..')` if it is really your only js in the script tag.

using innerHTML or in your case insertAdjacentHTML to add <script> tags to the document doesn't work because browsers historically try to prevent potential cross site script attacks (https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0)
What you could do is something like:

const s = document.createElement("script");
s.type = "module";
s.innerText = `import './components/nav-bar.js'`;
this.append(s);
// or simply directly without the script: `import('./comp..')` if it is really your only js in the script tag.

无法附加到自定义Web组件

巷子口的你 2025-02-19 04:59:58

这是解决方案(不需要额外的libs):

import os

somenumber = 1  # use number generated in your code
fpath = "C:/user/desktop/somefolder"

for full_fname in os.listdir(fpath):
    # `someword` is a file name without an extension in that context
    someword, fext = os.path.splitext(full_fname)
    old_fpath = os.path.join(fpath, full_fname)
    new_fpath = os.path.join(fpath, f"{someword} {somenumber}{fext}")
    os.rename(old_fpath, new_fpath)

Here is the solution (no extra libs needed):

import os

somenumber = 1  # use number generated in your code
fpath = "C:/user/desktop/somefolder"

for full_fname in os.listdir(fpath):
    # `someword` is a file name without an extension in that context
    someword, fext = os.path.splitext(full_fname)
    old_fpath = os.path.join(fpath, full_fname)
    new_fpath = os.path.join(fpath, f"{someword} {somenumber}{fext}")
    os.rename(old_fpath, new_fpath)

在Python中编辑CSV文件名以附加到当前文件名

巷子口的你 2025-02-19 02:42:47

这样的东西?

SQL> SET SERVEROUTPUT ON
SQL>
SQL> DECLARE
  2     clob_          VARCHAR2 (32000) := '!
  3  $HEADER_START=TRUE
  4  $SOURCE_REF1=45963
  5  $SOURCE_REF2=1
  6  $SOURCE_REF3=1
  7  $SOURCE_REF4=
  8  $SOURCE_REF_TYPE_DB=PURCHASE_ORDER
  9  $CONV_FACTOR=1
 10  $CONTRACT=3566
 11  $DESCRIPTION=EX 1000V 3x95mm² AL
 12  $LINE_END=TRUE
 13  $HEADER_END=TRUE
 14  ';
 15
 16     inParam1_      VARCHAR2 (32000) := '';
 17     inParam2_      VARCHAR2 (32000) := 'FALSE';
 18
 19     l_source_ref1  NUMBER;
 20     l_contract     NUMBER;
 21  BEGIN
 22     SELECT 11111, 22222
 23       INTO l_source_ref1, l_contract
 24       FROM DUAL;
 25
 26     clob_ :=
 27        REGEXP_REPLACE (clob_,
 28                        '\$SOURCE_REF1=\d+',                 --> escape $
 29                        '$SOURCE_REF1=' || l_source_ref1);
 30     clob_ :=
 31        REGEXP_REPLACE (clob_, '\$CONTRACT=\d+',             --> escape $
 32                               '$CONTRACT=' || l_contract);
 33
 34     DBMS_OUTPUT.put_line (clob_);
 35  END;
 36  /

结果:

!
$HEADER_START=TRUE
$SOURCE_REF1=11111                 --> new value here
$SOURCE_REF2=1
$SOURCE_REF3=1
$SOURCE_RE
F4=
$SOURCE_REF_TYPE_DB=PURCHASE_ORDER
$CONV_FACTOR=1
$CONTRACT=22222                    --> and here
$DESCRIPTI
ON=EX 1000V 3x95mm2 AL
$LINE_END=TRUE
$HEADER_END=TRUE


PL/SQL procedure successfully completed.

SQL>

Something like this?

SQL> SET SERVEROUTPUT ON
SQL>
SQL> DECLARE
  2     clob_          VARCHAR2 (32000) := '!
  3  $HEADER_START=TRUE
  4  $SOURCE_REF1=45963
  5  $SOURCE_REF2=1
  6  $SOURCE_REF3=1
  7  $SOURCE_REF4=
  8  $SOURCE_REF_TYPE_DB=PURCHASE_ORDER
  9  $CONV_FACTOR=1
 10  $CONTRACT=3566
 11  $DESCRIPTION=EX 1000V 3x95mm² AL
 12  $LINE_END=TRUE
 13  $HEADER_END=TRUE
 14  ';
 15
 16     inParam1_      VARCHAR2 (32000) := '';
 17     inParam2_      VARCHAR2 (32000) := 'FALSE';
 18
 19     l_source_ref1  NUMBER;
 20     l_contract     NUMBER;
 21  BEGIN
 22     SELECT 11111, 22222
 23       INTO l_source_ref1, l_contract
 24       FROM DUAL;
 25
 26     clob_ :=
 27        REGEXP_REPLACE (clob_,
 28                        '\$SOURCE_REF1=\d+',                 --> escape $
 29                        '$SOURCE_REF1=' || l_source_ref1);
 30     clob_ :=
 31        REGEXP_REPLACE (clob_, '\$CONTRACT=\d+',             --> escape $
 32                               '$CONTRACT=' || l_contract);
 33
 34     DBMS_OUTPUT.put_line (clob_);
 35  END;
 36  /

Result:

!
$HEADER_START=TRUE
$SOURCE_REF1=11111                 --> new value here
$SOURCE_REF2=1
$SOURCE_REF3=1
$SOURCE_RE
F4=
$SOURCE_REF_TYPE_DB=PURCHASE_ORDER
$CONV_FACTOR=1
$CONTRACT=22222                    --> and here
$DESCRIPTI
ON=EX 1000V 3x95mm2 AL
$LINE_END=TRUE
$HEADER_END=TRUE


PL/SQL procedure successfully completed.

SQL>

PL/SQL逃脱字符串用于字符串插值

巷子口的你 2025-02-18 12:41:50

功能 getDerivedStateFromProps 不起作用?

也许使用应该componentupdate

The function getDerivedStateFromProps don't work ?

Maybe use shouldComponentUpdate ?

可以使用getDerivedStateFromprops从道具中执行React状态更新

巷子口的你 2025-02-18 10:27:04
  repriteCond%{https} off
#rewriterule ^(。*)$ https://%{http_host}%{request_uri} [l,r = 301]
重写(。
 

您缺少参数之间的空间。 IE。 (。*)&lt; here&gt; https:// accid ... 。最终结果是,以上是什么都不做的,因为正则是不匹配的。但是,您还保留了检查HTTPS状态(HTTP的一部分到HTTPS规则)的条件,因此仅将HTTP重定向(而不是HTTPS)。

假设新域指向另一个服务器,那么您在旧主机上不需要任何一个。删除现有 .htaccess 文件的内容,然后使用简单的mod_alias redirect 指令:

# .htaccess at the old host/domain

# Redirect everything to the new domain
Redirect 301 / https://example.new/

redirect 指令是前缀匹配和比赛后的所有内容被传递到目标。例如。 https://example.old/foo/bar 被重定向到 https://example.new/foo/bar

首先用302(临时)重定向测试,以避免潜在的缓存问题。


在新主机...

# BEGIN Really Simple SSL Redirect 5.3.0
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/
#RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
RewriteRule (.*)https://accidentallydutch.com/$1 [L,R=301]
</IfModule>
# END Really Simple SSL Redirect

您再次缺少&lt; space&gt; ,如上所述。但是,本节由“非常简单的SSL”插件维护。无需更改它(您所做的任何更改都可能被插件覆盖)。

RewriteCond %{HTTPS} off
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule (.*)https://accidentallydutch.com/$1 [L,R=301]

You are missing a space between arguments. ie. (.*)<here>https://accid.... The net result is that the above will do nothing because the regex never matches. However, you have also kept the condition that checks the HTTPS status (part of the HTTP to HTTPS rule), so this would only redirect HTTP (not HTTPS).

Assuming the new domain points to a different server then you don't need any of this at the old host. Delete the contents of the existing .htaccess file and use a simple mod_alias Redirect directive instead:

# .htaccess at the old host/domain

# Redirect everything to the new domain
Redirect 301 / https://example.new/

The Redirect directive is prefix matching and everything after the match is passed through to the target. eg. https://example.old/foo/bar is redirected to https://example.new/foo/bar.

Test first with a 302 (temporary) redirect to avoid potential caching issues.


At the new host...

# BEGIN Really Simple SSL Redirect 5.3.0
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/
#RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
RewriteRule (.*)https://accidentallydutch.com/$1 [L,R=301]
</IfModule>
# END Really Simple SSL Redirect

You are missing a <space> again, as mentioned above. However, this section is maintained by the "Really Simple SSL" plugin. There's no real need to change it (and any changes you do make are likely to be overwritten by the plugin).

使用.htaccess不起作用将旧站点重定向到新站点

巷子口的你 2025-02-18 10:13:22

如果脚本执行顺序不是问题,则问题的另一个可能原因是该元素未正确选择:

  • getElementById 要求传递的字符串为ID verbatim ,别无其他。如果将传递的字符串前缀为,并且ID不会以##开头,则不会选择:

     &lt; div id =“ foo”&gt;&lt;/div&gt;
     
      //错误,选定的元素将为null:
      document.getElementById('#foo')
      // 使固定:
      document.getElementById('foo')
     

  • 类似地,对于 getelementsbyclassname < /code>,请勿将传递的字符串前缀

     &lt; div class =“ bar”&gt;&lt;/div&gt;
     
      //错误,选定的元素将不确定:
      document.getElementsByClassName('。bar')[0]
      // 使固定:
      document.getElementsByClassName('bar')[0]
     

  • 与querySelector,queryselectorall和jQuery一起,以匹配具有特定类名称的元素,直接将放在课堂上。同样,要将元素与特定ID匹配,请直接将放在ID之前:

     &lt; div class =“ baz”&gt;&lt;/div&gt;
     
      //错误,选定的元素将为null:
      document.queryselector('baz')
      $('baz')
      // 使固定:
      document.queryselector('。baz')
      $('。baz')
     

    在大多数情况下,此处的规则与CSS选择器相同,可以详细看到在这里

  • 要匹配具有两个或多个属性的元素(例如两个类名称,一个类名称和一个 data-属性),请在选择器中将每个属性的选择器彼此相邻放置string,没有将它们分开的空间(因为空间表示后代选择器)。例如,选择:

     &lt; div class =“ foo bar”&gt;&lt;/div&gt;
     

    使用查询字符串 .foo.bar 。选择

     &lt; div class =“ foo” data-bar =“ somedata”&gt;&lt;/div&gt;
     

    使用查询字符串 .foo [data-bar =“ somedata”] 。要选择&lt; span&gt; 下面:

     &lt; div class =“ parent”&gt;
        &lt; span data-username =“ bob”&gt;&lt;/span&gt;
      &lt;/div&gt;
     

    使用 div.parent&gt;跨度[data-username =“ bob”]

  • 大写和拼写对以上所有内容都很重要。如果大写不同或拼写不同,则不会选择元素:

     &lt; div class =“结果”&gt;&lt;/div&gt;
     
      //错误,选定的元素将为null:
      document.queryselector('。结果')
      $('。结果')
      // 使固定:
      document.queryselector('。结果')
      $('。结果')
     
  • 您还需要确保方法具有适当的资本化和拼写。使用:

    之一

      $(选择器)
    document.queryselector
    document.queryselectorall
    document.getElementsByClassName
    document.getElementsbytagname
    document.getElementById
     

    任何其他拼写或资本化都无法正常工作。例如, document.getElementByClassName 会丢弃错误。

  • 确保将字符串传递给这些选择器方法。如果将不是字符串的东西传递给 QuerySelector getElementById 等,它几乎可以肯定不会工作。

  • 如果您要选择的元素上的html属性被引号包围,则必须是平淡的引号(单个或double); '之类的卷曲引号,如果您尝试按ID,类或属性进行选择,将无效。

If script execution order is not the issue, another possible cause of the problem is that the element is not being selected properly:

  • getElementById requires the passed string to be the ID verbatim, and nothing else. If you prefix the passed string with a #, and the ID does not start with a #, nothing will be selected:

      <div id="foo"></div>
    
      // Error, selected element will be null:
      document.getElementById('#foo')
      // Fix:
      document.getElementById('foo')
    
  • Similarly, for getElementsByClassName, don't prefix the passed string with a .:

      <div class="bar"></div>
    
      // Error, selected element will be undefined:
      document.getElementsByClassName('.bar')[0]
      // Fix:
      document.getElementsByClassName('bar')[0]
    
  • With querySelector, querySelectorAll, and jQuery, to match an element with a particular class name, put a . directly before the class. Similarly, to match an element with a particular ID, put a # directly before the ID:

      <div class="baz"></div>
    
      // Error, selected element will be null:
      document.querySelector('baz')
      $('baz')
      // Fix:
      document.querySelector('.baz')
      $('.baz')
    

    The rules here are, in most cases, identical to those for CSS selectors, and can be seen in detail here.

  • To match an element which has two or more attributes (like two class names, or a class name and a data- attribute), put the selectors for each attribute next to each other in the selector string, without a space separating them (because a space indicates the descendant selector). For example, to select:

      <div class="foo bar"></div>
    

    use the query string .foo.bar. To select

      <div class="foo" data-bar="someData"></div>
    

    use the query string .foo[data-bar="someData"]. To select the <span> below:

      <div class="parent">
        <span data-username="bob"></span>
      </div>
    

    use div.parent > span[data-username="bob"].

  • Capitalization and spelling does matter for all of the above. If the capitalization is different, or the spelling is different, the element will not be selected:

      <div class="result"></div>
    
      // Error, selected element will be null:
      document.querySelector('.results')
      $('.Result')
      // Fix:
      document.querySelector('.result')
      $('.result')
    
  • You also need to make sure the methods have the proper capitalization and spelling. Use one of:

    $(selector)
    document.querySelector
    document.querySelectorAll
    document.getElementsByClassName
    document.getElementsByTagName
    document.getElementById
    

    Any other spelling or capitalization will not work. For example, document.getElementByClassName will throw an error.

  • Make sure you pass a string to these selector methods. If you pass something that isn't a string to querySelector, getElementById, etc, it almost certainly won't work.

  • If the HTML attributes on elements you want to select are surrounded by quotes, they must be plain straight quotes (either single or double); curly quotes like or will not work if you're trying to select by ID, class, or attribute.

为什么jQuery或诸如getElementById之类的DOM方法找不到元素?

巷子口的你 2025-02-18 05:43:28

您可以使用列表并创建 toggle(tag) is_selected(tag)函数用于切换和检查其状态,而不是为每个标签创建新变量。节目/隐藏逻辑仍然很复杂,但您也可以在后端生成它。

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

<div x-data="{
  tags: [],
  toggle(tag) {
    if (this.tags.includes(tag)) {
      this.tags = this.tags.filter(x => x != tag)
    }
    else {
      this.tags.push(tag)
    }
  },
  is_selected(tag) {
    return this.tags.includes(tag)
  }
}">

  <div>
    <button @click="toggle('tag1')" :style="is_selected('tag1') && {background: 'salmon'}">Tag 1</button>
    <button @click="toggle('tag2')" :style="is_selected('tag2') && {background: 'salmon'}">Tag 2</button>
    <button @click="toggle('tag3')" :style="is_selected('tag3') && {background: 'salmon'}">Tag 3</button>
    <button @click="toggle('tag4')" :style="is_selected('tag4') && {background: 'salmon'}">Tag 4</button>
  </div>
  <br>
  
  <div x-show="(is_selected('tag1') || is_selected('tag1')) && !(is_selected('tag3') || is_selected('tag4'))">
      Show if tag1 and/or tag2 is true. Hide if Tag3 and/or Tag4 is true
  </div>
  <div x-show="(is_selected('tag2') || is_selected('tag4')) && !(is_selected('tag1') || is_selected('tag3'))">
      Show if tag2 and/or tag4 is true. Hide if Tag1 and/or Tag3 is true
  </div>
  <br>
  
  <div x-text="`Selected tags: ${tags}`"></div>
</div>

Instead of creating a new variable for each tag, you can use a list and create toggle(tag) and is_selected(tag) functions for toggling and checking their state. The show/hide logic is still kinda complicated but you can generate it on the backend as well.

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

<div x-data="{
  tags: [],
  toggle(tag) {
    if (this.tags.includes(tag)) {
      this.tags = this.tags.filter(x => x != tag)
    }
    else {
      this.tags.push(tag)
    }
  },
  is_selected(tag) {
    return this.tags.includes(tag)
  }
}">

  <div>
    <button @click="toggle('tag1')" :style="is_selected('tag1') && {background: 'salmon'}">Tag 1</button>
    <button @click="toggle('tag2')" :style="is_selected('tag2') && {background: 'salmon'}">Tag 2</button>
    <button @click="toggle('tag3')" :style="is_selected('tag3') && {background: 'salmon'}">Tag 3</button>
    <button @click="toggle('tag4')" :style="is_selected('tag4') && {background: 'salmon'}">Tag 4</button>
  </div>
  <br>
  
  <div x-show="(is_selected('tag1') || is_selected('tag1')) && !(is_selected('tag3') || is_selected('tag4'))">
      Show if tag1 and/or tag2 is true. Hide if Tag3 and/or Tag4 is true
  </div>
  <div x-show="(is_selected('tag2') || is_selected('tag4')) && !(is_selected('tag1') || is_selected('tag3'))">
      Show if tag2 and/or tag4 is true. Hide if Tag1 and/or Tag3 is true
  </div>
  <br>
  
  <div x-text="`Selected tags: ${tags}`"></div>
</div>

alpine.js filter content by tags

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文