开发者

About Events to Textbox and Div

I have assigned a onClick event to textbox. When I am clicking on textbox, I want to execute the c开发者_开发知识库lick event of div also. How to do that in Javascript?. The div and textbox are not nested they are on different position in document.

Thanks in advance for the Help.


I would recommend using a function that is called by both.


You need to know even bubbling in order to do that.


I recommend reading PPK's blog post about events. It's a bit old, but it weathers the test of time well. See:

http://www.quirksmode.org/js/events_order.html


If the elements are nested the event will bubble up (if you aren't cancelling it) so:

<div onclick="foo()">
    <input type="text" onclick="bar()" />
  </div>

Will result in a call to bar then foo. This is a bit of a kludge though since you don't really want to have inline event binding if you can help it. This is one of those cases where use jquery might be appropriate since $('#mydiv, #myinput').click(baz) is quite clean.


Try this:

 function twoActions(){
  var textboxId = document.getElementById("textboxId");

  var divId = document.getElementById("divId");

   textboxId.style.border = "red"; // action one  

   divId.style.border = "red";  // action two

}

you tie this function to the textbox - onClick it will change the border color of the text box and that of the Div.


If you're not nesting the divs, you'll need to explicitly call the .click() of the div separately.

function textEvent() {
    // Do all the stuff you want to do for the textbox

    // Fire the event for the div too
    div = document.getElementById('#secondDiv');
    div.click();
}


I am reading it as if you have 2 different functions. We'll just say textbox(); and div();

your onclick for the textbox should read

onclick="textbox(); div();"

That should call both functions on the same event, where with the div you can put only the div() function or both like the example above. Just seperate the function calls with a semi-colon.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜