使用javascript只更改一个类的所有img src中的一个字符

时间:2016-05-04 14:38:36

标签: javascript html image

我想更改“car-image”类中所有图片的src。

但我不需要改变整个网址。我只想更改一个字符

我想编辑这个 -

<div class="car-image">
    <img src="/cars/3_large_1.png">
</div>

对此 -

<div class="car-image">
    <img src="/cars/3_large_2.png">
</div>

这种格式在本课程的所有图像中都很常见。 我试过这样的事情 -

var allsrc = document.getElementsByClassName('car-image');
allsrc[0].src="/cars/3_large_2.png";

这不起作用。 我怎么能在javascript中做到这一点?

6 个答案:

答案 0 :(得分:3)

你正在设置错误节点的src allsrc返回你的div而不是图像。

试试这个

 var new_json = {{"nodes": [{ "id": 124587, "name": "paper1", "citation": 5, "group": 1 },
{ "id": 178456, "name": "paper2", "citation": 8, "group": 2 }],
"links": [{ "source": 124587, "target": 178456, "name": "A-B-1", "value": 8 }]};

function load_graph(text) {
            var color = d3.scale.category20();           
            var data1 = {
                "nodes": [
                    { "id": 0, "name": "paper1", "citation": 5, "group": 1 },
                    { "id": 1, "name": "paper2", "citation": 8, "group": 2 },
                    { "id": 2, "name": "paper3", "citation": 12, "group": 3 },
                    { "id": 3, "name": "paper4", "citation": 25, "group": 4 },
                    { "id": 4, "name": "paper5", "citation": 15, "group": 5 },
                    { "id": 5, "name": "paper6", "citation": 5, "group": 1 },
                    { "id": 6, "name": "paper7", "citation": 8, "group": 2 },
                    { "id": 7, "name": "paper8", "citation": 12, "group": 3 },
                    { "id": 8, "name": "paper9", "citation": 25, "group": 4 },
                    { "id": 9, "name": "paper10", "citation": 15, "group": 5 }
                ],
                "links": [
                    { "source": 0, "target": 1, "name": "A-B-1", "value": 8 },
                    { "source": 0, "target": 1, "name": "A-B-2", "value": 24 },
                    { "source": 0, "target": 2, "name": "A-C-1", "value": 12 },
                    { "source": 0, "target": 2, "name": "A-C-3", "value": 44 },
                    { "source": 2, "target": 3, "name": "A-D-1", "value": 11 },
                    { "source": 2, "target": 3, "name": "A-D-2", "value": 35 },
                    { "source": 2, "target": 4, "name": "A-E-1", "value": 16 },
                    { "source": 2, "target": 4, "name": "A-E-5", "value": 30 },
                    { "source": 4, "target": 5, "name": "A-B-1", "value": 8 },
                    { "source": 4, "target": 5, "name": "A-B-2", "value": 24 },
                    { "source": 5, "target": 6, "name": "A-C-1", "value": 12 },
                    { "source": 5, "target": 6, "name": "A-C-3", "value": 44 },
                    { "source": 5, "target": 7, "name": "A-D-1", "value": 11 },
                    { "source": 5, "target": 7, "name": "A-D-2", "value": 35 },
                    { "source": 7, "target": 8, "name": "A-E-1", "value": 16 },
                    { "source": 7, "target": 8, "name": "A-E-5", "value": 30 },
                    { "source": 8, "target": 3, "name": "A-C-1", "value": 12 },
                    { "source": 8, "target": 3, "name": "A-C-3", "value": 44 },
                    { "source": 8, "target": 9, "name": "A-D-1", "value": 11 },
                    { "source": 8, "target": 9, "name": "A-D-2", "value": 35 }
                ]
            };

            // used to store the number of links between two nodes. 
            // mLinkNum[data.links[i].source + "," + data.links[i].target] = data.links[i].linkindex;
            var mLinkNum = {};

            // sort links first
            sortLinks();

            // set up linkIndex and linkNumer, because it may possible multiple links share the same source and target node
            setLinkIndexAndNum();

            var w = 960,
                h = 500;

            var force = d3.layout.force()
                          .nodes(d3.values(data1.nodes))
                          .links(data1.links)
                          .size([w, h])
                          .linkDistance(200)
                          .charge(-300)
                          .on("tick", tick)
                          .start();

            var svg = d3.select(".graphContainer").append("svg:svg")
                        .attr("width", w)
                        .attr("height", h);

            var path = svg.append("svg:g")
                          .selectAll("line")
                          .data(force.links())
                          .enter().append("svg:path")
                          .attr("class", "link")
                          .style("stroke-width", function (d) { return Math.sqrt(d.value); });


            var circle = svg.append("svg:g")
                            .selectAll("circle")
                            .data(force.nodes())
                            .enter().append("svg:circle")
                            .attr("r", function (d) { return (d.citation); })
                            .style("fill", function (d) { return color(d.group); })
                            .call(force.drag);

            var text = svg.append("svg:g")
                          .selectAll("g")
                          .data(force.nodes())
                          .enter().append("svg:g");

            // A copy of the text with a thick white stroke for legibility.
            text.append("svg:text")
                .attr("x", 8)
                .attr("y", ".31em")
                .attr("class", "shadow")
                .text(function (d) { return d.name; });

            text.append("svg:text")
                .attr("x", 8)
                .attr("y", ".31em")
                .text(function (d) { return d.name; });

            // Use elliptical arc path segments to doubly-encode directionality.
            function tick() {
                path.attr("d", function (d) {
                    var dx = d.target.x - d.source.x,
                        dy = d.target.y - d.source.y,
                        dr = Math.sqrt(dx * dx + dy * dy);
                    // get the total link numbers between source and target node
                    var lTotalLinkNum = mLinkNum[d.source.id + "," + d.target.id] || mLinkNum[d.target.id + "," + d.source.id];
                    if (lTotalLinkNum > 1) {
                        // if there are multiple links between these two nodes, we need generate different dr for each path
                        dr = dr / (1 + (1 / lTotalLinkNum) * (d.linkindex - 1));
                    }
                    // generate svg path
                    return "M" + d.source.x + "," + d.source.y +
                        "A" + dr + "," + dr + " 0 0 1," + d.target.x + "," + d.target.y +
                        "A" + dr + "," + dr + " 0 0 0," + d.source.x + "," + d.source.y;
                });

                // Add tooltip to the connection path
                path.append("svg:title")
                    .text(function (d, i) { return d.name; });

                circle.attr("transform", function (d) {
                    return "translate(" + d.x + "," + d.y + ")";
                });

                text.attr("transform", function (d) {
                    return "translate(" + d.x + "," + d.y + ")";
                });
            }

            // sort the links by source, then target
            function sortLinks() {
                data.links.sort(function (a, b) {
                    if (a.source > b.source) {
                        return 1;
                    }
                    else if (a.source < b.source) {
                        return -1;
                    }
                    else {
                        if (a.target > b.target) {
                            return 1;
                        }
                        if (a.target < b.target) {
                            return -1;
                        }
                        else {
                            return 0;
                        }
                    }
                });
            }

            //any links with duplicate source and target get an incremented 'linknum'
            function setLinkIndexAndNum() {
                for (var i = 0; i < data.links.length; i++) {
                    if (i != 0 &&
                        data.links[i].source == data.links[i - 1].source &&
                        data.links[i].target == data.links[i - 1].target) {
                        data.links[i].linkindex = data.links[i - 1].linkindex + 1;
                    }
                    else {
                        data.links[i].linkindex = 1;
                    }
                    // save the total number of links between two nodes
                    if (mLinkNum[data.links[i].target + "," + data.links[i].source] !== undefined) {
                        mLinkNum[data.links[i].target + "," + data.links[i].source] = data.links[i].linkindex;
                    }
                    else {
                        mLinkNum[data.links[i].source + "," + data.links[i].target] = data.links[i].linkindex;
                    }
                }
            }
        }

</script>

答案 1 :(得分:1)

  

我想要更改所有图像的src   &#39;汽车图像&#39;使用javascript的课程。

您可以为所有<img>类更改src car-image,如下所示:

&#13;
&#13;
var all = document.getElementsByClassName('car-image');

for(var i = 0; i < all.length; i++){
    var image = document.getElementsByClassName('car-image')[i].getElementsByTagName('img');
    image[0].setAttribute("src", "/cars/3_large_2.png");
}
&#13;
<div class="car-image">
  <img src="/cars/3_large_1.png">
</div>
<div class="car-image">
  <img src="/cars/5_large_1.png">
</div>
<div class="car-image">
  <img src="/cars/7_large_1.png">
</div>
<div class="car-image">
  <img src="/cars/9_large_1.png">
</div>
&#13;
&#13;
&#13;

(检查元素并查看新的src&#39;

答案 2 :(得分:1)

更优雅的解决方案是使用带有正则表达式的替换功能。如果你知道图像src模式和类似的更改适用于所有图像src,你可以构建一个正则表达式。在这种情况下,不是逐个更改每个图像src,而是可以迭代包含car-image类的元素,找出第一个childNode并更改src attr。

// find all elements that contains class car-image
var carImgDivs = document.getElementsByClassName('car-image');

// iterate over carImgDivs and execute an imediate function to just pass the
// childNode1 that is the image. Use replace function with regex to find out the
// changed image src value and set the changed src value to childNode1
for(var i = 0; i < carImgDivs.length; i++) (function(childNode1) {
  if(childNode1) { 
    var replacedSrc = childNode1.getAttribute('src').replace(/(_)(\d)/, "$12");
    childNode1.setAttribute("src", replacedSrc);
  }
})(carImgDivs[i].childNodes[1]);

对于像/cars/3_large_1.png这样的图像src,正则表达式(_)(\ d)匹配数字后面的下划线并捕获两者。替换字符串$1中的"$12"表示保持第一个捕获组(下划线)不变,而2表示用2替换第二个捕获组(一个数字) 。基本上,正则表达式与上面的图像src中的_1匹配。 _是第一个捕获组,1是第二个捕获组。因此,最后,图像src变为/cars/3_large_2.png

答案 3 :(得分:0)

使用(jQuery解决方案):$( "img:nth-child(1)" ).attr('src', <new_name>);

nth-child(i)表示i图像。

示例:

$(".car_image img:nth-child(1)").attr('src', '/cars/3_large_2.png');

要更改所有图片,只需删除:nth-child()

即可

答案 4 :(得分:0)

如果您include jquery in your page可以

$(".car-image img").attr("src", "/cars/3_large_2.png");

答案 5 :(得分:0)

这个怎么样?

var x = document.getElementsByClassName('car-image')[0]; 
var img = x.getElementsByTagName('img')[0];
img.src = "/cars/3_large_2.png";