我有一个 JavaScript 函数,我用它来更新隐藏字段,其中包含向用户显示的图像的文件名。这在具有单个图像和单个隐藏字段的页面上运行良好。我正在尝试对其进行自定义,以便可以在单个页面上使用它来更新多个隐藏字段,具体取决于它们是否存在。
Previously I tried to call separate functions从我的 onload
中用分号分隔。它适用于第一页/隐藏字段,但当第二页上的第一个隐藏字段不可用时,它会一直报错。
在这次尝试中,我尝试使用带有链接到隐藏字段 id 的 if 语句的单个函数,但不幸的是,我似乎无法让它在任何页面/隐藏字段上工作
谁能告诉我哪里出错了?我相信这样做是可能的,但我没有得到任何结果。谢谢
当前输出
<input id="id_9-slider_one_image" name="9-slider_one_image" type="hidden" />
<input id="id_10-slider_two_image" name="10-slider_two_image" type="hidden" />
<input id="id_11-slider_three_image" name="11-slider_three_image" type="hidden" />
期望的输出
<input id="id_9-slider_one_image" name="9-slider_one_image" type="hidden" value="P1DP.jpg"/>
<input id="id_10-slider_two_image" name="10-slider_two_image" type="hidden" value="P6D6.jpg"/>
<input id="id_11-slider_three_image" name="11-slider_three_image" type="hidden" value="P3D3.jpg"/>
我的代码
<div class="image_rating">
<img src="{% static "survey/images/pathone/" %}{{display_image}}" value="{{display_image}}" onload="updateInput(this)"/>
</div>
<script type="text/javascript">
function updateInput(ish) {
var valueAttribute = ish.getAttribute("value");
if($(this).attr("id") == "id_9-slider_one_image")
document.getElementById("id_9-slider_one_image").setAttribute(
"value", valueAttribute);
if($(this).attr("id") == "id_10-slider_two_image")
document.getElementById("id_10-slider_two_image").setAttribute(
"value", valueAttribute);
if($(this).attr("id") == "id_11-slider_three_image")
document.getElementById("id_11-slider_three_image").setAttribute(
"value", valueAttribute);
}
</script>
最佳答案
感谢这个问题和the highest voted answer在尝试设置值之前,我能够检查该 id 是否存在于页面中
{% if wizard.steps.current in steps %}
<div class="image_rating">
<img src="{% static "survey/images/pathone/" %}{{display_image}}" value="{{display_image}}" onload="updateInput(this)"/>
</div>
<script type="text/javascript">
function updateInput(ish) {
var valueAttribute = ish.getAttribute("value");
if (document.getElementById('id_9-slider_one_image')) {
document.getElementById("id_9-slider_one_image").setAttribute(
"value", valueAttribute)
}
if (document.getElementById('id_10-slider_two_image')) {
document.getElementById("id_10-slider_two_image").setAttribute(
"value", valueAttribute)
}
if (document.getElementById('id_11-slider_three_image')) {
document.getElementById("id_11-slider_three_image").setAttribute(
"value", valueAttribute)
}
</script>
关于javascript - 一个 JavaScript 函数,用于更新多个隐藏字段,具体取决于它们是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092952/