0

I'm trying to add an on click function to a div using these lines of code but the click event doesnt trigger the alert.

var str="<script>$(this).on(\"click\",function(){alert('hello');})";
str+="<";
str+="/script>";
$("div:contains('Send')").last().append(str);

I've also tried this and $(this)[0] but these give me the error this.on/ $(this)[0].on is not a function I don't know what Im doing wrong and would appreciate any and all help on the matter.

4
  • "<script>$(this).on(\"click\",function(){alert('hello');})"; what will this represent here? Commented Nov 6, 2015 at 11:47
  • im sorry I dont understand the question? Commented Nov 6, 2015 at 11:48
  • When you use this, it represents current object. So when you do obj.alert(), in alert, this will represent obj. Also for your case refer to this JSFiddle for reference. Hope it helps. Commented Nov 6, 2015 at 11:52
  • 1
    $("div:contains('Send')").last().on("click",function(){alert('hello');}) ? Commented Nov 6, 2015 at 11:54

3 Answers 3

1

Shouldn't have to go through the trouble of creating strings for script. You can just use jquerys .on and register it with a click event.

$("div:contains('Send')").last().on("click", function () {
    alert('hello');
})
Sign up to request clarification or add additional context in comments.

Comments

0

If you are using jQuery, you can add click event to all the div by using $("div") for selector (just remember to call the function after you load the div)

I have create an example of simple click function

$(".start").click(function() {
    $(this).toggleClass("onClick");
})

http://jsfiddle.net/7j6s2Lws/2/

The $(this) will identify which object is actually trigger the event, and choose it only. In my case, if you click on a div, it will change color (of it and only it)

Comments

0

i would choose a slightly different approach. i hope i understood your problem right even though i dont really get what you want to achieve by putting <script> into your string here... maybe this helps:

html

<div id='container'>
    <button>Send</button>
</div>

js

var $container = $("div:contains('Send')");
var elementToAppend = "<div class='myClass' style='width:100px; height:100px; border: 1px solid red'>added dynamically ... click me</div>";

appendToContainer($container, elementToAppend);
$('.myClass').click(function($element) {
    alert(123);
});

function appendToContainer($container, element) {
    $container.append(element);
}

fiddle

http://jsfiddle.net/2pofLnb7/2/

1 Comment

if you just want to add a clickhandler to anything existing then have a look at the fiddle/js/line5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.