将html标题转换为javascript变量

时间:2013-09-19 13:54:32

标签: javascript html variables var

如何从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",}

Titletext名称来自超链接锚点中的标题

我尝试了以下内容并且无效

JS

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

}

2 个答案:

答案 0 :(得分:0)

首先,您需要以某种方式识别<a>元素。最简单的方法是给它一个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);

我希望这就是你要求的,因为,如果我诚实,我不确定你想说什么。

答案 1 :(得分:0)

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

<强> 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",
}