从 DOM - Reasonml/BuckleScript querySelector 中选择元素
Selecting elements from the DOM - Reasonml/BuckleScript querySelector
您如何使用 Reason DOM 中的 select 项。我正在使用 bs-webapi 作为 DOM 绑定,这是我想要做的:
let parent = document |> Document.querySelector(".parent");
let child = Element.querySelector(".child", parent);
但是,BuckleScript 会抱怨,因为父对象的类型不正确。它说 parent 是 option(Dom.element)
类型,parent 应该是 Dom.element.t
。我是 Reason 的新手,正在努力学习。我不明白 option(Dom.element)
是什么意思或如何使上面的代码块工作。非常感谢任何帮助
您需要解包选项变体,我们可以使用开关并使用内置的 None/Some 变体。
您可以在此处找到有关选项变体的一些文档:https://reasonml.github.io/docs/en/newcomer-examples.html#using-the-option-type
这里有一些关于选项的更多文档:https://reasonml.github.io/docs/en/variant.html#option
为此,您需要将代码更改为如下所示:
let parent = document |> Document.querySelector(".parent");
let child = switch (parent) {
| Some(p) => switch (Element.querySelector(".child", p)) {
| Some(c) => c
| None => raise(Failure("Unable to find child selector"))
}
| None => raise(Failure("Unable to find parent selector"))
};
如果你想登录到控制台而不是失败,你需要 return 一个有效的 Dom.element.t
,这可能是这样的:
let emptyEl = document |> Document.createElement("noscript");
let parent = document |> Document.querySelector(".parent");
let child = switch (parent) {
| Some(p) => switch (Element.querySelector(".child", p)) {
| Some(c) => c
| None => {
Js.log("Unable to find child selector");
emptyEl;
}
}
| None => {
Js.log("Unable to find parent selector");
emptyEl;
}
};
然后您会想要检查您的子元素是否是 noscript
以查看您是否找到了您正在寻找的子元素。
您如何使用 Reason DOM 中的 select 项。我正在使用 bs-webapi 作为 DOM 绑定,这是我想要做的:
let parent = document |> Document.querySelector(".parent");
let child = Element.querySelector(".child", parent);
但是,BuckleScript 会抱怨,因为父对象的类型不正确。它说 parent 是 option(Dom.element)
类型,parent 应该是 Dom.element.t
。我是 Reason 的新手,正在努力学习。我不明白 option(Dom.element)
是什么意思或如何使上面的代码块工作。非常感谢任何帮助
您需要解包选项变体,我们可以使用开关并使用内置的 None/Some 变体。
您可以在此处找到有关选项变体的一些文档:https://reasonml.github.io/docs/en/newcomer-examples.html#using-the-option-type
这里有一些关于选项的更多文档:https://reasonml.github.io/docs/en/variant.html#option
为此,您需要将代码更改为如下所示:
let parent = document |> Document.querySelector(".parent");
let child = switch (parent) {
| Some(p) => switch (Element.querySelector(".child", p)) {
| Some(c) => c
| None => raise(Failure("Unable to find child selector"))
}
| None => raise(Failure("Unable to find parent selector"))
};
如果你想登录到控制台而不是失败,你需要 return 一个有效的 Dom.element.t
,这可能是这样的:
let emptyEl = document |> Document.createElement("noscript");
let parent = document |> Document.querySelector(".parent");
let child = switch (parent) {
| Some(p) => switch (Element.querySelector(".child", p)) {
| Some(c) => c
| None => {
Js.log("Unable to find child selector");
emptyEl;
}
}
| None => {
Js.log("Unable to find parent selector");
emptyEl;
}
};
然后您会想要检查您的子元素是否是 noscript
以查看您是否找到了您正在寻找的子元素。