문제

I'm trying to change the data-url with jQuery. Currently my code looks like this.

<div id="twitterButton" title="Tweet it on Twitter"><a href="https://twitter.com/share" id="tweet" class="twitter-share-button" data-url="" data-related="jasoncosta" data-lang="en" data-size="large" data-count="none">Tweet</a></div>

<script type="text/javascript">
$(document).ready(function () {
    $('#twitterButton').click(function () {
        $('#tweet').attr("data-url", "https://www.google.com/");
    });
});</script>

As you can see I left the url-data blank so I could be sure it is only getting set in the jQuery. However whenever I click the tweet button it always opens the window with the link for the current page that I was on. Can someone explain how I can set it to be something else via jQuery or javascript?

도움이 되었습니까?

해결책

You should use .data() for controlling data attributes. As Daniele states in that answer, you must also stop the event propogation on the a element using preventDefault().

$('#twitterButton').click(function (e) {
    $('#tweet').data('url',"https://www.google.com");
    e.preventDefault();
});

다른 팁

You must call the preventDefault() method to stop the propagation of the click event on the child a element:

Try this code:

$('#twitterButton').click(function (e) {
    $('#tweet').attr("data-url", "https://www.google.com/");
    e.preventDefault();
});

Good code

D.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top