Javascript:如何更改</p> <div>中的<p>内的文本,点击<a> inside a list

时间:2017-02-20 07:37:37

标签: javascript html

Onclick anchor tag 'CLICK ON ME' I want to change the text of p tag inside div....

<li class="class_1" id="item-1">
  <a href="http://somethingxyz.com/">
  <img src="http://somethingxyz.com/imaqges/image.png" class="mlt-lang">CLICK ON ME</a>
</li>

and the p tag in div element where i need to change the text is:-

<div class="footer_left">
    <p>This text needs to be change.</p>
</div>

5 个答案:

答案 0 :(得分:1)

您也可以尝试使用jQuery。

&#13;
&#13;
$(".class_1 > a").click(function(e) {
        e.preventDefault();
        $(".footer_left > p").text("This is New Text"); // Or $(".footer_left > p").html("This is New Text");
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<li class="class_1" id="item-1">
    <a href="http://somethingxyz.com/">
        <img src="http://somethingxyz.com/imaqges/image.png" class="mlt-lang">CLICK ON ME</a>
</li>


<div class="footer_left">
    <p>This text needs to be change.</p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试以下代码。如果您在Anchor标记中使用链接,它将重定向到给定的链接,因此您无法查看当前页面中的更改(尽管它已进行更改)

<script> 
function clickchange() {
        var ptag = document.getElementById('par1');
        ptag.innerHTML = 'Observe the Change';
    }
</script>

<li class="class_1" id="item-1">
  <a href="#" onclick="clickchange()">
  <img src="http://somethingxyz.com/imaqges/image.png" class="mlt-lang">CLICK ON ME</a>
</li>
and the p tag in div element where i need to change the text is:-

<div class="footer_left">
    <p id="par1">This text needs to be change.</p>
</div>

答案 2 :(得分:0)

首先,您必须bind a元素的点击事件处理程序。此外,您需要使用event.preventDefault()以防止元素的默认行为。

要更改文字,您可以使用innerHTML方法。

var a=document.getElementsByTagName('a')[0];
var p=document.querySelector('.footer_left p');
a.onclick=function(e){
   e.preventDefault();
   p.innerHTML='changed';
}
<li class="class_1" id="item-1">
  <a href="http://somethingxyz.com/">
  <img src="http://somethingxyz.com/imaqges/image.png" class="mlt-lang">CLICK ON ME</a>
</li>
and the p tag in div element where i need to change the text is:-

<div class="footer_left">
    <p>This text needs to be change.</p>
</div>

答案 3 :(得分:0)

您可以这样做:使用QuerySelector

  <img src="http://somethingxyz.com/imaqges/image.png" class="mlt-lang" onclick="myFunction()">CLICK ON ME</a>


     function myFunction(){

         var p = document.querySelector(".footer_left p");
         p.innerHTML = "your custom content";
     }

答案 4 :(得分:0)

function ConvertToAnchor ()
{

    var paragraphs = document.getElementsByTagName('p');
    for (var i =0 ; i < paragraphs.length ; i++)
    {
       var textt = paragraphs[i].textContent;

        paragraphs[i].innerHTML = '<a href=http://www.' + textt + '.com>' + textt + '</a>'

    }
}