2

我是 StackExchange 的新手。我在 JavaScript 中有一个非常基本的问题。

我创建了简单的 JavaScript 函数来更改文本的颜色,在onClick我想更改最后一个单词的同一函数中使用

这是示例

<!doctype html>
<head>
<title>
    Sample Javascript
</title>
<script type="text/javascript">
    function colorchange(myid)
    {
        x = document.getElementById('sample_text');
        x.style.color = "red";
        x.style.fontWeight = "bold";

        text = document.getElementById('sample_text1');

    }

</script>
</head>
<body>
    <div id="sample_text" onClick="colorchange(1)">Welcome to <span onClick="colorchange(2)" id="sample_text1">Mahaweb</span></div>
</body>
</html>

请帮助我,我想用相同的功能更改跨度内部内容。

4

5 回答 5

2
<!doctype html>
<head>
<title>
    Sample Javascript
</title>
<script type="text/javascript">
function colorchange()
{
x = document.getElementById('sample_text');
x.style.color = "red";
x.style.fontWeight = "bold";

document.getElementById('sample_text1').innerHTML = "text";

}

</script>
</head>
<body>
<div id="sample_text" onClick="colorchange()">Welcome to <span onClick="colorchange()" id="sample_text1">Mahaweb</span></div>
</body>
</html>
于 2013-08-16T19:03:16.663 回答
0

如果我理解正确,您想更改跨度的内部文本。由于您已经选择了span( var text),请尝试:

text.innerHTML="desiredText";

于 2013-08-16T19:00:46.753 回答
0

您可以通过更改文本元素的属性“innerHTML”来实现此目的。

就像是:

text.innerHTML = "your_change";

但这是非常基本的东西。确保检查一些文件;)

于 2013-08-16T19:02:39.503 回答
0
<script type="text/javascript">
    function colorchange(myid)
    {
        x = document.getElementById('sample_text');
        x.style.color = "red";
        x.style.fontWeight = "bold";

        text = document.getElementById('sample_text1');
        if(myid==2){
           text.innerHTML="YOUR TEXT HERE";  
        }

    }

</script>
于 2013-08-17T17:56:23.900 回答
-3

我相信这就是你所追求的(我正在使用 jQuery,一个 javascript 库,它使这类事情变得更容易)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$('#sample_text').click(function(){
     $(this).find('span').css('color', 'red').css('font-weight', 'bold');
});

</script>
于 2013-08-16T19:02:34.057 回答