【问题标题】:Returning the URL from href attribute从 href 属性返回 URL
【发布时间】:2019-08-18 14:02:10
【问题描述】:

我正在尝试从 href 属性中获取 url 并附加并返回它,但我不断收到“无法读取 null 的属性 'href'”。

我尝试使用 document.getElementsByClassName("CLASS").href 获取值,但返回未定义,然后当我使用 id 时,我得到上面的 null 错误。

这是我的 HTML:

<a class="js-link-name" id="js-link" href="{{ route('report.file.list')}}">Click Me</a>

@push('scripts')
    <script>
        $(function () {
            var questionnaires = [];

            @foreach($vm->getQuestionnaires() as $questionnaire)
            questionnaires.push(new window.app.locationReports.Questionnaire('{{ $questionnaire->getValue()  }}', '{{ $questionnaire->forDisplay() }}'));
            @endforeach

            new window.app.locationReports.LocationTiles($('.js-location-tiles'), $('.js-file-download-link'), $('.js-legend-trigger'), '{{ $vm->getUserViewPreferenceValue() }}', questionnaires, '{{ route('api.v1.reports.customer-satisfaction.recommend-to-others') }}', '{{ route('report.customer-satisfaction.locations.data.view-preference') }}');
        });
    </script>
@endpush

这是我的 JS 函数:

buildLocationReportListUrl(){
        let newUrl = URI(document.getElementById('js-link').href).addSearch(this.locationId);

        return newUrl;
    }

【问题讨论】:

  • 该函数何时运行?
  • @Herohtar 我在控制台中调用它。一旦我让它工作,我将创建一个单独的函数,将新 URL 添加到 href 属性。
  • 对我来说很好:jsfiddle.net/khrismuc/r8qdfjxc 请创建一个minimal reproducible example,以便我们重现您遇到的错误。该错误清楚地指向在&lt;a&gt; 存在之前运行的脚本。
  • 在您的脚本标签中添加defer 以确保
  • @ChrisG 我相信你是对的。我添加了一些代码,以便您帮助我了解问题所在。

标签: javascript laravel routes href


【解决方案1】:

您的代码不完整。但是,当我尝试对您的函数进行一些修改时,它会返回 URL。

function buildLocationReportListUrl(){
    let newUrl = document.getElementById('js-link').href;

    return newUrl;
}

//执行返回URL的函数

buildLocationReportListUrl();

希望这会有所帮助! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多