【问题标题】:taking the html title to a javascript variable将 html 标题转换为 javascript 变量
【发布时间】:2013-09-24 15:39:50
【问题描述】:

如何从 JS 文件中获取 titleText "Some Name" 中的变量以填充或从 HTML 代码中的超链接 "sometitle" 中获取标题?

JS

var randomtext={ titleText:"Some Name",}

HTML

<a class="css" title="sometitle" href="#">Your HTML Here</a>

我希望 JS 然后更改为:

JS

var randomtext={ titleText:"sometitle",}

标题文本名称来自超链接锚中的标题

我尝试了以下方法,但没有成功

JS

    var randomtext={ 
titleText:document.getElementsByClassName('css')[0]; randomtext.titleText = anchor.getAttribute('title');,
title2: "name1",
title3: "name3",
title4: "name4",

}

【问题讨论】:

    标签: javascript html variables var


    【解决方案1】:

    首先,您需要以某种方式识别&lt;a&gt; 元素。最简单的方法是给它一个 ID。

    然后,使用document.getElementById,您可以访问脚本中的超链接。完成后,您可以使用setAttributegetAttribute 访问其标题。

    HTML

    <a id="myLink" class="css" title="sometitle" href="#">Your HTML Here</a>
    

    JavaScript

    var link = document.getElementById("myLink");
    
    // Take the title from the link
    var randomText = { titleText: link.getAttribute("title") };
    
    // Change the link's title
    link.setAttribute("title", randomText.titleText);
    

    我希望这是你所要求的,因为老实说,我不确定你想说什么。

    【讨论】:

    • @DavidSmith 确实如此。看看我做的这个例子:jsbin.com/akEHELI/1 |它输出链接标题。
    【解决方案2】:

    这假设您想要获取锚点上的“title”属性,并使用它来设置randomtext 对象上的titleText 属性的值:

    JS

    var randomtext={ titleText:"Some Name"}
    // a more specific class name or id would be better suited here
    var anchor = document.getElementsByClassName('css')[0];  
    randomtext.titleText = anchor.getAttribute('title');
    

    jsFiddle

    更新

    我不确定您为什么要在对象定义中包含所有逻辑,但您当前的 javascript 无效。如果您在创建 randomText 对象时绝对必须为 titleText 属性分配一个值,那么以下应该可以工作:

       var randomtext={ 
         // this immediately invokes a function 
         // which looks for the first anchor
         // and returns it's title attribute
         // that attribute is then assigned to the titleText property
         // on the object.
         titleText:(function () {
             var anchor = document.getElementsByClassName('css')[0];     
             return anchor.getAttribute('title');
         })(),
        title2: "name1",
        title3: "name3",
        title4: "name4",
    }
    

    【讨论】:

    • 你说得对,我想从锚点上取标题,用它来设置JS脚本中属性的值。我尝试了两种代码,但它们都不起作用。
    • 你写的JS代码无效。您可以按照我在答案中编写的代码重写您的代码,或者将其包装在 iife 中并返回您想要分配给 titleText 属性的值。另外,你的 JS 必须是一个。在 DOM 加载后包含或 b.使用“就绪”函数等待 DOM 加载完毕。
    • 我没有重写它的选项,因为它是一个相当大的代码。我希望我可以在 titletext 之后插入一些东西:就可以了。通过添加以下行获取有效的页面标题。 (titleText: document.title,) 但我需要它来获取锚标题而不是页面标题。你可能需要解释我不明白的最后一部分
    • @DavidSmith 对不起,如果我不清楚。您尝试的 javascript 代码(在您编辑的问题中列出)无效。属性分配中不能有多个 javascript 语句。我已经用您的代码的更正版本更新了我的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多