使用JavaScript获取当前URL,然后在html代码中使用派生值

使用JavaScript获取当前URL,然后在html代码中使用派生值,javascript,facebook,facebook-javascript-sdk,Javascript,Facebook,Facebook Javascript Sdk,我有一个简单的问题,但作为一个JavaScript新手,我不知道如何实现我的发现 我发现了一个小snippit,它使用JavaScript拉入当前URL,并将该值加载到一个变量: <script type="text/javascript" language="javascript"> window.onload = function () { var currentUrl = window.location.href; } </script> 给你的d

我有一个简单的问题,但作为一个JavaScript新手,我不知道如何实现我的发现

我发现了一个小snippit,它使用JavaScript拉入当前URL,并将该值加载到一个变量:

<script type="text/javascript" language="javascript">
  window.onload = function () {
    var currentUrl = window.location.href;
  }
</script>

给你的
div
一个id:

<div id="fb-comments" class="fb-comments"

你也许可以这样做-

<div id="myCommentBox" class="fb-comments" data-href="**currentUrl**" data-width="470" data-num-posts="2"></div>

var element = document.getElementById('myCommentBox');
element.setAttribute("data-href", currentUrl); 

var元素=document.getElementById('myCommentBox');
setAttribute(“数据href”,currentUrl);

请注意,我给了
一个
id
属性,以便使用
getElementById
很容易找到它。请记住,一旦更改了
data href
属性,就需要调用它来重新呈现注释框。

在这个问题中,我认为:

// gets all elements of class-name 'fb-comments' from the document
var fbComments = document.getElementsByClassName('fb-comments');

// iterates through each of those elements
for (var i = 0, len = fbComments.length; i<len; i++) {
    // and sets the 'data-href' attribute to be the value held by the
    // the currentUrl variable
    fbComments[i].setAttribute('data-href', currentUrl);
}
参考资料:


那么我应该将数据href=”“部分留空吗?comments插件告诉我“该插件需要一个href参数”。这个partiuclar JavaScript只需将属性设置为变量中的任何值。如果一个值已经存在,这将简单地重写它,因此如果需要,您可以将其设置为占位符值,通常是
#
,但这取决于您。谢谢您的提示。我的HTML编辑器正在删除该字段,因为我将其留空。插入一个“#”,一个voiala
<div id="myCommentBox" class="fb-comments" data-href="**currentUrl**" data-width="470" data-num-posts="2"></div>

var element = document.getElementById('myCommentBox');
element.setAttribute("data-href", currentUrl); 
// gets all elements of class-name 'fb-comments' from the document
var fbComments = document.getElementsByClassName('fb-comments');

// iterates through each of those elements
for (var i = 0, len = fbComments.length; i<len; i++) {
    // and sets the 'data-href' attribute to be the value held by the
    // the currentUrl variable
    fbComments[i].setAttribute('data-href', currentUrl);
}
// gets all div elements within the document
var divs = document.getElementsByTagName('div');

// iterates through each of those div elements, and
for (var i = 0, len = divs.length; i<len; i++) {
    // if the class attribute contains a string equal to 'fb-comments'
    if (divs[i].className.indexOf('fb-comments') !== -1) {
        // sets the 'data-href' attribute to be equal to the value held
        // by the currentUrl variable
        divs[i].setAttribute('data-href', currentUrl);
    }
}