我有一个数组 <img .../>
-strings,我想将一个数字附加到 foo
中选定的属性。我编写了这段代码作为示例,其中 my_imgs
是 <img .../>
的数组-字符串:
<html>
<head>
<title>Append integer into the 'foo'-attribute of an 'img'-tag - Test</title>
<script>
function my_function(some_img, some_integer){
//magic happens :-(
return some_img_with_appended_integer;
}
</script>
</head>
<body>
<script>
var my_imgs = ["<img src='1.png' foo='99 1 33' bar='qwertz1' harhar='yxcvb1' />",
"<img src='2.png' foo='2 3' bar='qwertz2' harhar='yxcvb2' someother='x' />",
"<img src='3.png' foo='9 7 2' bar='qwertz3' harhar='yxcvb3' />"];
console.log("my_imgs = " + my_imgs);
my_function(my_imgs[0],"987"); // --> must return: "<img src='1.png' foo='99 1 33 987' bar='qwertz1' harhar='yxcvb1' />"
my_function(my_imgs[1],"76"); // --> must return: "<img src='2.png' foo='2 3 76' bar='qwertz2' harhar='yxcvb2' someother='x' />"
my_function(my_imgs[2],"345"); // --> must return: "<img src='3.png' foo='9 7 2 345' bar='qwertz3' harhar='yxcvb3' />"
</script>
</body>
我基本知道these tools有必要解决这个问题,但我正在努力解决我的问题,因此想寻求一些帮助。
最佳答案
You can achieve this using
createElement
which will create newDOM element
.append
theimage
element in created element usinginnerHTML
and then you can find that element usinggetElementsByTagName
and usingDOM node
methods likegetAttribute
andsetAttribute
to manipulateattributes
.
试试这个:
function my_function(some_img, some_integer) {
var elem = document.createElement('div');
elem.innerHTML = some_img;
var image = elem.getElementsByTagName('img')[0];
var attribute = image.getAttribute('foo');
image.setAttribute('foo', attribute + ' ' + some_integer);
return image.outerHTML;
}
var my_imgs = ["<img src='1.png' foo='99 1 33' bar='qwertz1' harhar='yxcvb1' />",
"<img src='2.png' foo='2 3' bar='qwertz2' harhar='yxcvb2' someother='x' />",
"<img src='3.png' foo='9 7 2' bar='qwertz3' harhar='yxcvb3' />"
];
var modified = my_function(my_imgs[0], "987");
alert(modified);
关于Javascript - img 字符串数组将数字附加到特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34763473/