Как изменить onclick через javascript

Javascript изменить onclick в html коде JavaScript Решение и ответ на вопрос 1661627

Доброго времени суток !

Столкнулся с такой проблемой , с помощью средства JavaScript нужно изменить onClick в html коде
на помощь пришла данная статейка : http://javascript.ru/tutorial/dom/modify

HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript edit onClick</title>
<script type="text/javascript">
    function FunA()
    {
        var button = document.getElementById('A')
        button.id = 'idB'
        button.className = 'classB'
        button.onclick = 'FunB()'
        button.innerHTML = 'Выполнить FunB'
    }
    function FunB()
    {
        var button = document.getElementById('B')
        button.id = 'idA'
        button.className = 'classA'
        button.onclick = 'FunA()'
        button.innerHTML = 'Выполнить FunA'
    }
</script>
</head>
<body>
    <button id="idA" class="classA" onclick="FunA()">Выполнить FunA</button>
</body>
</html>

в общем при первом нажатие , button меняет параметры на id=»idB» и class=»classB» но всё равно onclick=»FunA»

скорее всего я неверный аргумент указал . Дело в том что если подумать по сути логике , есть такие аргументы :

Javascript
1
2
3
    button.id = ' '
    button.className = ' '
    button.style = ' '

вот и подумал что button.onclick изменит параметр <button onclick=»»> </button>

в общем подскажите пожалуйста , как изменить значения onclick с помощью JavaScript ?

и ещё вопрос :
я заметил в некоторых уроках то что что пишут в конце аргумента символ

;
то есть :

Javascript
1
2
3
4
5
6
7
8
    function FunA()
    {
        var button = document.getElementById(' '); <- Вот тут
        button.id = ' '; <- и тут 
        button.className = ' '; <- и тут
        button.onclick = ' '; <- и тут
        button.innerHTML = ' '; <- ну и здесь
    }; <- разве тут тоже нужно писать символ ; ??????

и обязательно писать var ???

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

If you need to change or assign a value to the onclick attribute of a DOM element, you have two options; you can use either plain Javascript or the popular jQuery library. In this article, we’ll take a look at both methods and some common mistakes that are easy to make.

Assigning the onclick attribute inline

If you decided to set the onclick attribute inline (directly in the HTML element’s declaration), your first instinct might be to try something like this:

<p id="myElement" onclick="function(){alert('Hello World');}" > Click me! </p>

Unfortunately, that would be incorrect. Why? Because you’re merely declaring a function when the button is clicked, not actually running it. To avoid this, you can put your function in a closure. A closure is a bit of Javascript code that runs as soon as the compiler sees it. This is the correct way of setting the onclick attribute of a specific element:

<p id="myElement" onclick="(function(){alert('Hello World');})()" > Click me! </p>

Note the closure syntax, which looks like this: ()(…), where “…” is the code or function you want executed.

Passing in a function name

If you have a function that already exists in your Javascript somewhere else, you can also set a call to that function inline by passing its name into the onclick attribute, like this:

<p id="myElement" onclick="sayHello()" > Click me! </p>

Make sure your sayHello() function is defined somewhere above the element it’s called from in your HTML file; otherwise, you’ll receive a “[function name] is undefined” exception.

Using Javascript to change the onclick attribute

Changing the onclick attribute with plain Javascript is fairly straightforward. You don’t need to worry about closures, as Javascript handles that automatically if you’re changing the onclick attribute from a script. You can do it like this:

document.getElementById("myElement").onclick = function() {
 alert("Goodbye world!");
};

Using jQuery to change the onclick attribute

The popular library jQuery makes it somewhat simpler to change the onclick attribute. The following code is equivalent to the previous, Javascript-only code.

$("#myElement").click(function() {
 alert("Hello World");
});

Final notes

Be aware that you’ll want to put any DOM-modifying functions inside a function that executes when the DOM is ready to be manipulated. Otherwise you’ll be attempting to modify DOM elements that don’t actually exist yet.

I’ve tried looking for answer for this and can’t seem find one specific to this.

My site has a button, which looks like this:

<input class="btn btn-success" onclick="w.start()" type="button" value="Start" id='start' />

And on click I want it to change to «Stop» and I want the onclick function to change to onclick="w.stop()" instead of w.start() and I want the class to change to from btn-success to btn-danger (bootstrap)

I can get the name to change fine using this jQuery:

$(function () {
    $('#start').click(function () {
        $(this).val() == "Start" ? play_int() : play_pause();
    });
});

function play_int() {
    $('#start').val("Stop");
    // do start
}

function play_pause() {
    $('#start').val("Start");
    // do stop
}

But how do I get the onclick function and the class to change?

Especially the onclick function :)

Henrik Andersson's user avatar

asked Aug 2, 2013 at 14:37

Josh's user avatar

2

You got a lot of good advice about how to handle the issue in different ways — but nothing answering your specific question about how to change the onclick. This is a useful ability in many contexts — so even if you take somebody else’s counsel about the general approach, I wanted to answer your specific question.

Here’s code that I’ve tested and found to work:

<script>
function play_int() {
    alert("play_int was executed");
    $("#start").val("Stop");
    $("#start").attr("onclick", "play_pause()");
    // do start
}

function play_pause() {
    alert("play_pause was executed");
    $("#start").val("Start");
    $("#start").attr("onclick", "play_int()");
    // do stop
}
</script>

<input class="btn btn-success" onclick="play_int();" type="button" value="Start" id='start' />

answered Aug 2, 2013 at 15:05

Joe DeRose's user avatar

Joe DeRoseJoe DeRose

3,3383 gold badges23 silver badges33 bronze badges

1

I think it would be easiest to just start with two buttons, one called start and one called stop, and have stop initially hidden.

In your start function add

$('#start').hide();
$('#stop').show();

Then your old button, with its name and function disappear and your new button with the proper name and proper function appears.

answered Aug 2, 2013 at 14:42

Developer Gee's user avatar

Instead of changing the function it is calling, use an «if» statement. Not as familiar with jquery as I am raw, js, but I think it would be something like this.

if($('#start').val = "start"){
   function play_int() {
        $('#start').val("Stop");
        // do start
   }
}
if($('#start').val = "stop"){
   function play_pause() {
        $('#start').val("Start");
        // do stop
   }
}

answered Aug 2, 2013 at 14:43

Jacques ジャック's user avatar

Jacques ジャックJacques ジャック

3,6522 gold badges19 silver badges43 bronze badges

$(function(){$('#start').click(function() {
   if($(this).val() == "Start"){
       $(this).val("Stop");
       play_int();
   } else {
       $(this).val("Start");
       play_pause();
   }
});

answered Aug 2, 2013 at 14:44

Guillaume Lhz's user avatar

Just use one event handler. I would use jQuery to detect which class is active on your button. Then you can perform the appropriate actions. You don’t need to set onclick in your element if you use this.

$(function () {
    $('#start').on('click', function() {
        if($(this).is('.btn-success')){
            $(this).removeClass('.btn-success').addClass('.btn-danger').val('Stop');
            //Do Start
        }else{
            $(this).removeClass('.btn-danger').addClass('.btn-success').val('Start');
            //Do Stop
        }
    });
});

answered Aug 2, 2013 at 14:45

Fillmore's user avatar

Why not call a toggle function each time your button is clicked and let it handle the conditional.

function toggleChange(event){
  if($('#start').val()=="Stop";
     $('#start').val("Start");
     $('#start').addClass('newClass')
     $('#start').removeClass('oldClass')
   }
   else{
      $('#start').val("Stop");
      $('#start').addClass('newClass')
      $('#start').removeClass('oldClass')
   }
}

answered Aug 2, 2013 at 14:47

alQemist's user avatar

alQemistalQemist

3624 silver badges13 bronze badges

<input class="btn btn-success" onclick="w.start()" type="button" value="Start" id='btn' />

 $(function () {
  $('#btn').click(function () {
    var opn=$(this).val();
    switch(opn){
      case 'start':
      $(this).val("stop").removeClass('.btn-success').addClass('.btn-danger').click(w.stop); 
      break;

      case 'stop':
      $(this).val("start").removeClass('.btn-danger').addClass('.btn-success').click(w.start); 
      break;

  }
});
});

answered Aug 2, 2013 at 14:52

I took a look at your responses and found a solution that fits best for me:

$(function(){$('#start').click(function() {
    $(this).val() == "Start" ? play_int() : play_pause();                           
    });
});

function play_int() {
    $('#start').val("Stop");
    $('#start').addClass('btn-danger');
    $('#start').removeClass('btn-success');
    w.start();
}

function play_pause() {
    $('#start').val("Start");
    $('#start').addClass('btn-success');
    $('#start').removeClass('btn-danger');
    w.stop();
}

The w.stop() and w.start() are functions of another bit of js that starts the timer (this is for a timer app) :)

Feel free to give me feedback on my solution.

answered Aug 2, 2013 at 15:02

Josh's user avatar

JoshJosh

5,8198 gold badges28 silver badges43 bronze badges

This is a no jquery solution

HTML

<input class="btn-success" onclick="callme(this);" type="button" value="Start"/>

JAVASCRIPT

var callme = (function() {
    var start = true;
    return function(me) {
        if(start) {
            me.value = "Stop";
            me.className = "btn-danger";
            w.start();
        } else {
            me.value = "Start";
            me.className = "btn-success";;
            w.stop();
        }
        start = !start;
    };
}());

Here is the fiddle http://jsfiddle.net/HhuNU/

answered Aug 2, 2013 at 15:02

Logan Murphy's user avatar

Logan MurphyLogan Murphy

6,0503 gold badges24 silver badges41 bronze badges

I’ve tried looking for answer for this and can’t seem find one specific to this.

My site has a button, which looks like this:

<input class="btn btn-success" onclick="w.start()" type="button" value="Start" id='start' />

And on click I want it to change to «Stop» and I want the onclick function to change to onclick="w.stop()" instead of w.start() and I want the class to change to from btn-success to btn-danger (bootstrap)

I can get the name to change fine using this jQuery:

$(function () {
    $('#start').click(function () {
        $(this).val() == "Start" ? play_int() : play_pause();
    });
});

function play_int() {
    $('#start').val("Stop");
    // do start
}

function play_pause() {
    $('#start').val("Start");
    // do stop
}

But how do I get the onclick function and the class to change?

Especially the onclick function :)

Henrik Andersson's user avatar

asked Aug 2, 2013 at 14:37

Josh's user avatar

2

You got a lot of good advice about how to handle the issue in different ways — but nothing answering your specific question about how to change the onclick. This is a useful ability in many contexts — so even if you take somebody else’s counsel about the general approach, I wanted to answer your specific question.

Here’s code that I’ve tested and found to work:

<script>
function play_int() {
    alert("play_int was executed");
    $("#start").val("Stop");
    $("#start").attr("onclick", "play_pause()");
    // do start
}

function play_pause() {
    alert("play_pause was executed");
    $("#start").val("Start");
    $("#start").attr("onclick", "play_int()");
    // do stop
}
</script>

<input class="btn btn-success" onclick="play_int();" type="button" value="Start" id='start' />

answered Aug 2, 2013 at 15:05

Joe DeRose's user avatar

Joe DeRoseJoe DeRose

3,3383 gold badges23 silver badges33 bronze badges

1

I think it would be easiest to just start with two buttons, one called start and one called stop, and have stop initially hidden.

In your start function add

$('#start').hide();
$('#stop').show();

Then your old button, with its name and function disappear and your new button with the proper name and proper function appears.

answered Aug 2, 2013 at 14:42

Developer Gee's user avatar

Instead of changing the function it is calling, use an «if» statement. Not as familiar with jquery as I am raw, js, but I think it would be something like this.

if($('#start').val = "start"){
   function play_int() {
        $('#start').val("Stop");
        // do start
   }
}
if($('#start').val = "stop"){
   function play_pause() {
        $('#start').val("Start");
        // do stop
   }
}

answered Aug 2, 2013 at 14:43

Jacques ジャック's user avatar

Jacques ジャックJacques ジャック

3,6522 gold badges19 silver badges43 bronze badges

$(function(){$('#start').click(function() {
   if($(this).val() == "Start"){
       $(this).val("Stop");
       play_int();
   } else {
       $(this).val("Start");
       play_pause();
   }
});

answered Aug 2, 2013 at 14:44

Guillaume Lhz's user avatar

Just use one event handler. I would use jQuery to detect which class is active on your button. Then you can perform the appropriate actions. You don’t need to set onclick in your element if you use this.

$(function () {
    $('#start').on('click', function() {
        if($(this).is('.btn-success')){
            $(this).removeClass('.btn-success').addClass('.btn-danger').val('Stop');
            //Do Start
        }else{
            $(this).removeClass('.btn-danger').addClass('.btn-success').val('Start');
            //Do Stop
        }
    });
});

answered Aug 2, 2013 at 14:45

Fillmore's user avatar

Why not call a toggle function each time your button is clicked and let it handle the conditional.

function toggleChange(event){
  if($('#start').val()=="Stop";
     $('#start').val("Start");
     $('#start').addClass('newClass')
     $('#start').removeClass('oldClass')
   }
   else{
      $('#start').val("Stop");
      $('#start').addClass('newClass')
      $('#start').removeClass('oldClass')
   }
}

answered Aug 2, 2013 at 14:47

alQemist's user avatar

alQemistalQemist

3624 silver badges13 bronze badges

<input class="btn btn-success" onclick="w.start()" type="button" value="Start" id='btn' />

 $(function () {
  $('#btn').click(function () {
    var opn=$(this).val();
    switch(opn){
      case 'start':
      $(this).val("stop").removeClass('.btn-success').addClass('.btn-danger').click(w.stop); 
      break;

      case 'stop':
      $(this).val("start").removeClass('.btn-danger').addClass('.btn-success').click(w.start); 
      break;

  }
});
});

answered Aug 2, 2013 at 14:52

I took a look at your responses and found a solution that fits best for me:

$(function(){$('#start').click(function() {
    $(this).val() == "Start" ? play_int() : play_pause();                           
    });
});

function play_int() {
    $('#start').val("Stop");
    $('#start').addClass('btn-danger');
    $('#start').removeClass('btn-success');
    w.start();
}

function play_pause() {
    $('#start').val("Start");
    $('#start').addClass('btn-success');
    $('#start').removeClass('btn-danger');
    w.stop();
}

The w.stop() and w.start() are functions of another bit of js that starts the timer (this is for a timer app) :)

Feel free to give me feedback on my solution.

answered Aug 2, 2013 at 15:02

Josh's user avatar

JoshJosh

5,8198 gold badges28 silver badges43 bronze badges

This is a no jquery solution

HTML

<input class="btn-success" onclick="callme(this);" type="button" value="Start"/>

JAVASCRIPT

var callme = (function() {
    var start = true;
    return function(me) {
        if(start) {
            me.value = "Stop";
            me.className = "btn-danger";
            w.start();
        } else {
            me.value = "Start";
            me.className = "btn-success";;
            w.stop();
        }
        start = !start;
    };
}());

Here is the fiddle http://jsfiddle.net/HhuNU/

answered Aug 2, 2013 at 15:02

Logan Murphy's user avatar

Logan MurphyLogan Murphy

6,0503 gold badges24 silver badges41 bronze badges

Событие onclick в javascript и jquery на примерах

Такое простое событие, как onclick в javascript, может быть вызвано несколькими способами и скрыает некоторые тонкости. Событие происходит при клике по элементу левой кнопкой мыши. Стоит заметить, что при клике происходит так же ещё два события, а именно нажатие на кнопку мыши и её отжатие.

событие onclick в javascript

Все примеры будем рассматривать на теге «a» (ссылку). Пусть это не смущает, с другими тегами будет работать аналогичным образом.

Самый простой способ повесить событие onclick, это прописать его непосредственно в html теге:

<a href="#" onclick="alert('Пример 1 сработал'); return false;">Пример 1</a>

Код в действии:

В примере при нажатии на ссылку появляется всплывающее окно с сообщением. Дополнительно к действию мы прописали «return false;». Это требуется чтобы предотвратить переход по ссылке после срабатывания события «onclick». В других элементах (где нет аттрибута href) это можно опустить.

Рассмотренный вариант можно использовать если событие содержит мало кода. Иначе, следует обратить внимание на другие способы.

Выносим код события onclick в javascript-функцию

Следующий способ хорош тем, что мы отделяем javascript-код от html тегов. В теге прописываем название функции, а саму функцию выносим в отдельный блок:

<script>
function ChangeColor(Element) {
	if (Element.style.color == 'green') Element.style.color = 'red';
	else Element.style.color = 'green';
	return false;
}
</script>

<a href="#" style="color: green;" onclick="return ChangeColor(this);">Изменить цвет</a>

Код в действии:

Но и здесь всё не идеально. Что делать, если событие требуется повесить на все ссылыки сайта, а их сотни? Кажется что это трудно, а на деле — меньше десяти строк кода. Задача решается с помощью селекторов. В примере опять будем производить действия с тегом «a», но ничего не мешает использовать вместо ссылки «img» или «div».

Вешаем onclick на элемент из javascript-кода

Рассмотим еще один способ, на мой взгляд, самый практичный и надежный. Хорош он тем, что событие можно повесить на множество элементов. Для этого требуется выбрать при помощи javascript-селекторов элементы, к которым требуется применить событие onclick.

<script>
//дожидаемся полной загрузки страницы
window.onload = function () {

    //получаем идентификатор элемента
    var a = document.getElementById('switch');
    
    //вешаем на него событие
    a.onclick = function() {
        //производим какие-то действия
        if (this.innerHTML=='On') this.innerHTML = 'Off';
        else this.innerHTML = 'On';
        //предотвращаем переход по ссылке href
        return false;
    }
}
</script>

<a id="switch" href="#">On</a>

Код в действии:

Нажмите на ссылку: On

Выбору элементов по селекторам можно посвятить отдельную тему, могу сказать только то, что согласно новой спецификации HTML5, их выбор стал прост и в javascript. Если Вы знакомы с jquery или CSS, то выбрать нужные элементы для Вас не составит труда. Например, так просто можно выбрать все элементы с классом «link» и повесить на них нужное действие:

//выбираем нужные элементы
var a = document.querySelectorAll('.link');
    
//перебираем все найденные элементы и вешаем на них события
[].forEach.call( a, function(el) {
    //вешаем событие
    el.onclick = function(e) {
        //производим действия
    }
});

Применяем jQuery

Если в проекте используется библиотека jQuery, то можно ещё упростить код. Рассмотрим два самых распространенных способа:

$(function(){
    $(".link").click(function() {
        //действия
    });
});

И ещё один вариант, который идентичен предыдущему.

$(function(){
    $(".link").on("click", function(){
        //действия
    });
});

С обработчиком «on()» лучше ознакомиться отдельно, так как он несет в себе много полезного функционала. Например, возможность указать через пробел несколько событий к которым будет применяться действие, делегировать события на дочерние элементы, а так же он полезен если необходимо повесить событие на динамически добавляемые элементы, которых изначально нет на странице.

Понравилась статья? Поделить с друзьями:
  • Как изменить ods на xls
  • Как изменить ns сервера reg ru
  • Как изменить ns записи wix
  • Как изменить npc sims 4
  • Как изменить nginx conf