简体   繁体   English

将 HTML <a>href 属性添加到 Javascript 不起作用</a>

[英]Adding HTML <a> href Attribute to Javascript is not working

I am trying to implement a Live Search using Javascript for my Django Project, I search by words is working but I am only capable of getting Titles only as a result.我正在尝试使用 Javascript 为我的 Django 项目实施实时搜索,我按单词搜索是有效的,但我只能作为结果获得标题。 I am trying to add the Href so that It can direct the title to the url.我正在尝试添加 Href,以便它可以将标题指向 url。

Here is what I have tried:这是我尝试过的:

class Item(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(blank=False, upload_to=upload_design_to)
    price = models.DecimalField(decimal_places=2, max_digits=100)
    discount_price = models.DecimalField(decimal_places=2, max_digits=100, blank=True, null=True)
    timestamp = models.DateTimeField(default=timezone.now)

    def get_absolute_url(self):
        return reverse("store:product-detail", kwargs={'slug': self.slug})

Here is the views.py这是views.py

class ItemListView(ListView):
    model = Item
    paginate_by = 12
    template_name = "store/product_list.html"
    ordering = ['-timestamp']

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder)
        return context

Here is the template.html这里是模板。html

<input id="search_here" class="mb-2 form-control" placeholder="Type to search...">

<!--Card-->
<div id="box" class='row card-group'>
{% for item in object_list %}
  <div class="col-4 mb-3">
    <div class="card h-100">
        <a href="{{item.get_absolute_url}}">
      <embed src="{{ item.image.url }}" class="card-img-top" alt="..."/>
        </a>
      <div class="card-body">
        <h5 class="card-title">{{ item.title }}</h5>
          <p class="card-text">
        {% if item.description %}
            {{ item.description }}
        {% endif %}
        </p>
      </div>
      <div class="card-footer">
        <small class="text-muted">{{ item.timestamp }}</small>
      </div>
    </div>
  </div>
{% endfor %}
</div>
<!--Card-->

Here is the JS这是JS

<script>
    const data = '{{qs_json}}'

    const rdata = JSON.parse(data.replace(/&quot;/g, '"'))
    console.log(rdata)

    const input = document.getElementById('search_here')
    console.log(input)

    let filteredArr = []

    input.addEventListener('keyup', (e)=>{
        box.innerHTML = ""
        filteredArr = rdata.filter(store=> store['title'].includes(e.target.value))
        console.log(filteredArr)
        
        var url = "{{item.get_absolute_url}}"; 
        
        if (filteredArr.length > 0){
            filteredArr.map(store=>{
                box.innerHTML += `<a href="url"><br>${store['title']}<br></a>`
            })
        } else {
            box.innerHTML = "<b>No results found...</b>"
        }
    })
</script>

I am currently reciving an error:我目前收到一个错误:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/url

My question: How to add a link to direct to {{item.get_absolute_url}} using JS我的问题:如何使用 JS 添加指向{{item.get_absolute_url}}的链接

The current code:当前代码:

box.innerHTML += `<a href="url"><br>${store['title']}<br></a>`

is linking to the string literal "url".链接到字符串文字“url”。

Since var url contains the URL you want to link to, this change will create the <a> link with the href set to the value of url :由于var url包含您要链接到的 URL,因此此更改将创建<a>链接,其 href 设置为url

box.innerHTML += `<a href="${url}"><br>${store['title']}<br></a>`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM