对于我的代码,点击GET DATA
时我想获得element[0]
===> 1.png
,该怎么办?
function xx_fn() {
var image_pack_val = document.getElementById("image_pack").value;
var image = [image_pack_val][0]
alert(image);
}
<div onclick="xx_fn()">
GET DATA
</div>
<br>
<input type="hidden" id="image_pack" value="'1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png','10.png'">
答案 0 :(得分:1)
使用替换和拆分
您可能想要使用按钮而不是点击div
function xx_fn() {
var image_pack_val = document.getElementById("image_pack").value;
var image = image_pack_val.replace(/'/g,"").split(",")[0]
console.log(image);
}
<div onclick="xx_fn()">
GET DATA
</div>
<br>
<input type="hidden" id="image_pack" value="'1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png','10.png'">
答案 1 :(得分:1)
您可以匹配数据并获取 n 元素。
function xx_fn() {
var image_pack_val = document.getElementById("image_pack").value,
allImages = image_pack_val.match(/[^',]+/g);
console.log(allImages);
}
<button onclick="xx_fn()">GET DATA</button>
<br>
<input type="hidden" id="image_pack" value="'1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png','10.png'">
答案 2 :(得分:0)
只需删除单引号'
,然后在逗号,
上拆分。
function xx_fn() {
let imageNameList = document.getElementById("image_pack").value;
// remove all single quotes `'` and split on commas `,`
let imageNames = imageNameList.replace(/'/g, "").split(",");
console.log(imageNames[0]);
}
<div onclick="xx_fn()">
GET DATA
</div>
<br>
<input type="hidden" id="image_pack" value="'1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png','10.png'">
答案 3 :(得分:-1)
您的代码将获得整个字符串而不是拆分值。所以拆分字符串并传递适当的索引以获取图像名称
function xx_fn(index) {
var image_pack_val = document.getElementById("image_pack").value;
var image = image_pack_val.split(',')[index]//this should be the index of element clicked
alert(image);
}