获取文本并输入属性值

时间:2011-09-11 15:23:24

标签: javascript

我想从“p”标签之间获取文本并将其放在标题值中。

之前:

<option title="" value="Put Text">Put Text</option>

后:

<option title="$1,179.83" value="Put Text">Put Text</option>


任何人都知道可以实现此目的的JavaScript吗?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Get text and put in attribute value</title>
</head>

<body>


<div class="Text">
 <p>$1,179.83</p>
</div>


<form action="">

  <fieldset>

    <select class="putText" name="put-Text">
      <option title="" value="Put Text">Put Text</option>
    </select>

  </fieldset>

</form> 


</body>
</html>



* ** * ** * ** * ** * ** * ** * ** * ** * ** * ** 更新2011-09-13 * ** * ** * ** * ** * ** * ** * ** * ** * ** * **

代码现在正在运作。该代码也适用于ie6-8:

GET TEXT AND PUT IN ATTRIBUTE VALUE

3 个答案:

答案 0 :(得分:1)

为选项

添加ID
<option id="an_option" title="" value="Put Text">Put Text</option>

或者像这样

var an_option = document.getElementsByClass("putText")[0].getElementsByName("option")[0];

$ 1,179.83保存在

var vall = document.getElementsByClass("Text")[0].getElementsByName("p")[0].textValue;

通过

设置标题
document.getElementById("an_option").title = vall;
// or
an_option.title = vall;

但请注意,按类别进行的处理是模糊的,很容易被误认为
如果您需要正确地解决它(读取ID和CLASS属性之间的差异)

,最好使用ID

答案 1 :(得分:0)

是的..使用jQuery它很简单:

$('.putText').attr('title', $('.Text p').text());

答案 2 :(得分:0)

应该适用于IE4 +和NS7 +的所有浏览器

对于较新的浏览器,document.getElementsByClassName内置于

DEMO HERE

window.onload=function() {
  var pTag = document.getElementsByClassName("Text")[0].getElementsByTagName("p")[0];
  var amount = pTag.innerHTML; 
 // not sure title is useful on option in all browsers
  document.getElementsByTagName('option')[0].title=amount;
}    

旧版浏览器的额外代码

if (!document.getElementsByClassName)
  document.getElementsByClassName=function (oElm, strTagName, strClassName){
/*
Written by Jonathan Snook, http://www.snook.ca/jonathan
Add-ons by Robert Nyman, http://www.robertnyman.com
*/        
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for(var i=0; i<arrElements.length; i++){
    oElement = arrElements[i];
    if(oRegExp.test(oElement.className)){
        arrReturnElements.push(oElement);
    }
}
return (arrReturnElements)

}