无法使用 Bold 的 Shopify 产品选项获取 textarea 的值

Cannot get value of textarea with Shopify Product Options by Bold

我试图通过 Shopify Product Options by Bold and it is currently not working. I am able to get the value of a textarea locally, but I can not get the value when I move the code over to Shopify. I have looked here and 获取文本区域的值,但无济于事。

相关代码如下:

document.getElementById("248832").onkeyup=function(){getVal()};
var textbox = document.getElementsByName("properties[Message Body]")[0].value;

这是我试图获取

值的文本区域
<textarea data-option-key="ta_248832" id="248832" class="bold_option_child shapp_full_width " name="properties[Message Body]"></textarea>

当我在 Shopify 上尝试 运行 这个时,我收到一条错误消息 "Uncaught TypeError: Cannot set property 'onkeyup' of null",尽管我确实注意到有一次 shopify 运行 如下 jQuery 代码,这可能是导致我的问题的原因:

<script>
jQuery('#248832').change(function (){conditional_rules(7437760391);})
</script>

我正在尝试获取文本区域的值,这样我就可以 运行 获取所述文本区域中的字数。

如有任何帮助,我们将不胜感激!

解决方案

您正在尝试使用类似于 jQuery 方法的东西,但没有 jQuery:

document.getElementById("248832").onkeyup=function(){getVal()};

而 DOM 元素没有 onkeyup 方法。应该是

jQuery("#248832").on("keyup",function(){getVal()});

补充说明

即使不使用推荐的'.on'方法,您也必须将其写成

jQuery("#248832").keyup(function(){getVal()});

(docs),不像

jQuery("#248832").onkeyup(function(){getVal()});

如果您想使用 DOM 方法,那就是

document.getElementById("248832").addEventListener("keyup",function(){getVal()});

此外,您可能是将此作为最小示例编写的,但是您只调用 getVal() 并且不将值传递到某处这一事实听起来很奇怪,尽管我不知道是什么 getVal() 确实如此。

查看作为 null 返回的元素是否已加载。处于类似情况的其他人通过最后加载脚本来解决此问题。希望这对您有所帮助:)