如何获取点击的html元素并进行编辑?

时间:2017-06-06 06:19:04

标签: javascript jquery html javascript-events

我想获取点击的html元素,并在一段时间后进行编辑。

我尝试了什么?

我尝试了下面的一个,但我可以用html文本格式获得确切的html元素,但我无法改变它。如何更改值。

var _targetevent;

$( "body" ).click(function( event ) {
  _targetevent=event;
  console.log( "clicked: " + event.target); //<p>This is the old one</p>
});

function undateit()
{
  _targetevent.target="<b>This is the new div</b>";
}

1 个答案:

答案 0 :(得分:1)

1.在undateit()

内拨打click()

2.使用innerHTML_targetevent.target

实施例: -

&#13;
&#13;
var _targetevent;

$( "body" ).click(function( event ) {
  _targetevent=event;
  console.log( "clicked: " + event.target.id); //get id of the clicked element
  undateit(); //call function on click
});

function undateit(){
  //use outerHTML to completly replace div with new-one
  
  _targetevent.target.outerHTML="<b>This is the new div</b>";
  
  /* if you want to change only content inside element then use inner HTML
  
  _targetevent.target.innerHTML="<b>This is the new div</b>"; //use innerHTML
  
  */
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="mydiv">Check change</div>
</body>
&#13;
&#13;
&#13;