Getting function contents in onclick attribute in my html using jQuery

What?! I know what a bad idea.

Firstly, I can’t control the output of html, it is from the supplier, and it is created through their crazy system with which our company agrees. (not to mention the situation, I know that this is not optimal)

In html, I have:

<a id="notify" onclick="location.href='index.php?foo=bar';return false;" href="javascript:;">Notify!</a>

In my JS if I do this:

console.log($("#notify").attr("onclick"))

I get:

onclick(event)

Which makes sense, but I need to change the onclick attribute, so it reads something like:

onclick="location.href='index.php?foo=bar&zoobazz=moo';return false;"

even better if I could remove onclick and replace the value of the href attribute with location.href.

+3
source share
7 answers

This will give you the function in line

$("#notify").attr("onclick").toString()

After that grep url

+5
source

, , onclick , . , , . , "click" "onclick" ( jQuery JS), ".toString()" . , , , - "location.href= '.......".

. , .

<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    var $target = $("#notify");
    var funcBody = $target.attr("onclick").toString().split("\n")[1].split(";")[0];
    $target.attr("onclick","").attr("href", funcBody);
});
</script>
</head>
<body>
<a id="notify" onclick="location.href='index.php?foo=bar';return false;" href="javascript:;">Notify!</a>
</body>
</html>
+3

onclick, $( "# foo" ). click = ''; href, , .attr(, ); http://docs.jquery.com/Attributes http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax p >

$('#foo').click = '';
$('#foo').attr('href', 'whateveryousetitto');
+2
source
document.getElementById('notify').onclick = function() {location.href='index.php?foo=bar&zoobazz=moo';return false;};
+2
source

Whether there is a

$("#notify").click(function() { $("#notify").attr("onclick", "location.href='index.php?foo=bar&zoobazz=moo';"); return false;}) 

not do what you need?

+2
source

I might read too much on this question, but I think the OP is asking how to get the event code so that it can be manipulated, not just replaced. When specifying "index.php? Foo = bar", I don't think the value of bar is known. If this is a known value, then why read the onclick value at all?

+1
source
alert($('#notify').click);

?

+1
source

Source: https://habr.com/ru/post/1722033/


All Articles