использование <a>для запуска функции () - PullRequest
0 голосов
/ 25 января 2011

Мне было интересно, будет ли эта ссылка вызывать нужную мне функцию?

<a href="http://catalog.bitsltd.us/power_strips#replaced" onclick="document.getElementById('caShip').function caShip()" id="caShip">Some Text</a>

и это функция, которую я хочу вызвать ... Может кто-нибудь сказать мне, почему она также не работает?

<script type="text/javascript">
$(function caShip(){
    $('#caShip').replaceWith('Some HTML (the new HTML has an id of replaced)');
});
</script>

Когда ссылка нажата, она переходит к href, который является той же страницей и идентификатором, но он не заменяет новым HTML, который является

ОБНОВЛЕНИЕ: ЭТО РАБОЧИЙ КОД:

JS

<script type="text/javascript">
$(document).ready(function(){
    //Hide Canadian Information
    $('.locationDiv').hide();

    //bind the links click events
    $('.locLink').click(function(){       
        $('#1').hide();
        $('#desc_' + $(this).attr('title')).show();
    });
});     

</script>

HTML

<a href="javascript:void(0);" title="can" class="locLink" id="1">Canadian Customers Click Here Before Ordering!</a>
<div id="desc_can" class="locationDiv">
    <table class="contentpaneopen">
      <tr>
        <td class="contentheading" width="100%">Attention Canadian Customers!
        </td>
      </tr>
    </table>

    <table class="contentpaneopen">
      <tr>
        <td valign="top" >
        <span class="body">Please note that there are fees associated with shipping to Canada from the US that are <b><u><i><font color="red">NOT</font></i></u></b> included in the cost of the shipping or the cost of the unit. These cost are to be paid for by the purchaser. Here are some tips for shipping to Canada:
        <br />
        <br />
        -USPS methods are cheap but very unreliable. <b>Border fees</b> are not charged using USPS, only UPS or Fed Ex (which are the most reliable).
        <br />
        -<b>Customs fees</b> can sometime run <b>up to 50%</b> of the purchase price (UPS/FedEx).
        <br />
        -Smart Strips are available from a Canadian dealer. Visit our <a href="index.php?Itemid=146" title="Store Locator" target="_blank">Store Locator</a> to find a local seller.
        <br />
        -Customers with a UPS or FedEx account may ship on their account and assume all fees with no delays.
        <br />
        -Canadian customers selecting UPS or FedEx will have to pick the package up at their local station and pay the fees. So you order it online, but still have to drive and pay to pick it up unless you used your own UPS/Fed Ex account.</span>
        </td>
      </tr>
    </table>
</div>

Я не использовал CSS, потому что без него могу добиться того, что мне нужно. Спасибо всем, кто пытался мне помочь с этим !!!.

Ответы [ 5 ]

4 голосов
/ 25 января 2011

Нет.

Избавьтесь от встроенного атрибута onclick и просто сделайте это:

<script type="text/javascript">
$(function(){
    $('#caShip').click(function() {
        $(this).replaceWith('<div id="' + this.hash.slice(1) + '">some HTML</div>');
           // uncomment the next line if you want the hash to actually appear.
        // window.location.hash = this.hash;

           // prevent the page from reloading
        return false;
    });
});
</script>

Если вы хотите, чтобы он был встроенным, вы можете просто сделать это:

<a href="http://catalog.bitsltd.us/power_strips#replaced" onclick="caShip.call(this);" id="caShip">Some Text</a>


<script type="text/javascript">
function caShip(){
    $(this).replaceWith('<div id="' + this.hash.slice(1) + '">some HTML</div>');
}
</script>

РЕДАКТИРОВАТЬ: Исправлена ​​ошибка, при которой hash из элемента Anchor использовалось для создания нового элемента с этим идентификатором, поскольку именно это подразумевает текст, используемый для замены.

1 голос
/ 25 января 2011

Поскольку вы используете jQuery, вы должны сделать что-то вроде этого:

<a href="http://catalog.bitsltd.us/power_strips#replaced" id="caShip">Some Text</a>

jQuery

<script type="text/javascript">
$(function(){       
    $('#caShip').click(function() {
        if($(this).attr('href').indexOf("#") != -1) {
            $('#caShip').replaceWith('<div>Test</div>');
        }
    });
});
</script>

РЕДАКТИРОВАТЬ: Обновил jQuery для решения вашейкомментарий.Это работает в моем очень простом тестировании.

1 голос
/ 25 января 2011
<a href="http://catalog.bitsltd.us/power_strips#replaced" onclick="caShipFunc();" id="caShip">Some Text</a>


<script type="text/javascript">
  function caShipFunc(){
      $('#caShip').replaceWith('Some HTML (the new HTML has an id of replaced)');
  }
</script>
0 голосов
/ 25 января 2011

Попробуйте это ...

HTML

<a href="#replaced" id="caShip">Some Text</a>

JS

$('#caShip').click(function(){
    $(this).text('Some HTML (the new HTML has an id of replaced)');
});

http://jsfiddle.net/8bUKs/1/

0 голосов
/ 25 января 2011

Вы неправильно используете jQuery и фактически не объявляете функцию.

Запись $(function someName() { ... }) создает выражение именованной функции и передает его в функцию $.Он не объявляет повторно используемую функцию;тогда вы не можете написать someName().

Кроме того, ваш вызов в обработчике onclick совершенно неверен.
Чтобы вызвать функцию, вы должны просто вызвать ее (onclick="caShip();");Вы не можете комбинировать его с getElementById.

. Правильный способ сделать это - добавить обработчик click, используя jQuery:

$(function() { 
    $('#caShip').click(function() {
        $(this).replaceWith('Some HTML (the new HTML has an id of replaced)');
    });
});
...