如何在元素的属性末尾添加值?-javascript

how to add values to the end of an attribute of an element? - javascript

本文关键字:添加 -javascript 属性 元素      更新时间:2023-09-26

我知道还有其他方法可以解决这个问题,但这个问题突然出现在我的脑海中,我找不到答案。

我已经为属性的值循环了对象的值。我得到了值,想把它传递到元素的属性中,但属性中已经有值了,我希望对象中的属性值成为属性值的一部分。

让我们以youtube视频ID为例

在javascript中,这里存储youtube 的视频ID

request.execute(function(response){
    var results = response.result;
    $.each(results.items, function(index, item){
        var videoId = item.id.videoId;
    });
});

在html中使用iframe

<iframe width="640" height="360" src="https://www.youtube.com/embed/VIDEOID" frameborder="0" allowfullscreen></iframe>

上面,我们可以看到,如果js中的videoId插入到html中的VIDEOID中,那么视频将显示在html页面上。

如何使用普通的javascript/jQuery将videoId值传递到VIDEOID

为iframe设置一个id,就像一样

<iframe width="640" height="360" src="" frameborder="0" id = "yt_iframe" allowfullscreen></iframe>

并将其添加到您的jQuery 中

$("#yt_iframe").attr("src", "http://youtube.com/embed/" + videoId)

我还没试过,但应该试一下。

让我们假设,我有一个Iframes,它的属性叫做VideoID,里面有一些值

现在我想把VideoID的值附加到src中,我将使用以下方法。

//Looping through all the iframes    
$("iframe").each(function(){
   //appending the value if video ID to the SRC    
   $(this).attr('src',$(this).attr('src')+$(this).attr('VideoID'));
});

希望这会有所帮助。